2015-04-28 128 views
1

任何幫助,將不勝感激。如何在用戶點擊鼠標的面板上創建彩色圓點?我可以獲取鼠標點擊的座標並通過消息框輸出,但我無法在用戶點擊的面板上繪製點。我有這些代碼嘗試。在點擊事件中畫一個點

Private Sub createDot(x, y) 
    MsgBox(x & " " & y) 
    Dim myGraphics As Graphics = Me.CreateGraphics 

    Dim myPen As Pen 

    myPen = New Pen(Drawing.Color.Maroon, 20) 

    myGraphics.DrawRectangle(myPen, x, y, 1, 1) 

End Sub 

Private Sub Panel1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseClick 
    missed += 1 
    lblMissed.Text = missed 
    Dim x, y As Integer 
    x = e.X.ToString 
    y = e.Y.ToString 
    createDot(x, y) 
End Sub 

謝謝!

+0

什麼是ToString? x,y必須是整數而不是字符串!你應該在'MsgBox','MsgBox(x.ToString()&「)&y.ToString())' –

回答

3

三件事改變Me.CreateGraphicsPanel1.CreateGraphics

刪除的ToString:

1.如果你畫面板上,你應該使用Panel1.CreateGraphics不是Me.CreateGraphics
2.筆的寬度要大一點。使用1而不是
3.Do不是X,Y轉換爲字符串,並將它傳遞給createDot

注意:
只要面板無效(例如您移動另一個窗口在它)網點將消失。繪圖代碼應該在Panel1_Paint事件中(Scott Chamberlain)

Private Sub createDot(ByVal x As Integer, ByVal y As Integer) 

    MsgBox(x.ToString & " " & y.ToString) 
    Dim myGraphics As Graphics = Panel.CreateGraphics 

    Dim myPen As Pen 

    myPen = New Pen(Drawing.Color.Maroon, 1) 

    myGraphics.DrawRectangle(myPen, x, y, 1, 1) 

End Sub 

Private Sub Panel1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseClick 
    missed += 1 
    lblMissed.Text = missed 

    createDot(e.x, e.y) 
End Sub 
+2

4.這種方法不會很好,因爲一旦面板失效(例如你移動另一個窗口將其移開)點將消失。繪圖代碼應該在'Panel1_Paint'事件中,鼠標單擊應該排隊繪製事件讀取的某些數據結構,以便它知道在哪裏繪製,然後調用'Panel1.Invalidate'。 –

+0

然後就可以這樣做......創建全局變量x,y並在'mouse_down'事件和'paint event'中更改那裏的值。使用'e.CreateGraphics'繪製 –

+0

謝謝。更改爲Panel1.CreateGraphics使其工作。 – Ibanez1408

0

如果你想創建面板上的點,你應該從 ​​ y=e.Y