天天看點

執行個體107滑鼠畫線

    控件的MouseDown事件處理過程青兩個參數,一個是sender,一個是MouseEventArgs類的事件。

    MouseEventArgs類是定義在System.Windows.Forms中的一個類,它由同一個名稱空間下的EventArgs繼承而來。

    MouseEventArgs類的主要屬性有:

  • Button,表示被按下的滑鼠鍵;
  • Clicks,表示滑鼠單擊次數;
  • X,擷取滑鼠單擊的x坐标;
  • Y,擷取滑鼠單擊的y坐标。

    Graphics類中定義的DrawLines用于按照數組中給定的點序列繪制折線。

Graphics.DrawLines 方法

繪制一系列連接配接一組 Point 結構的線段。

重載

DrawLines(Pen, Point[]) 繪制一系列連接配接一組 Point 結構的線段。
DrawLines(Pen, PointF[]) 繪制一系列連接配接一組 PointF 結構的線段。
執行個體107滑鼠畫線

滑鼠左鍵開始,右鍵結束

Public Class Form1
    Dim myGraph As Graphics
    Dim myPen As New Pen(Brushes.Red, 3)
    Dim pointPath() As Point
    Dim pointNum As Integer = 0

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        myGraph = PictureBox1.CreateGraphics
    End Sub

    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        If e.Button = MouseButtons.Left Then
            If pointNum <= 0 Then
                ReDim pointPath(0)
            Else
                ReDim Preserve pointPath(pointPath.GetUpperBound(0) + 1)
            End If
            pointPath(pointPath.GetUpperBound(0)).X = e.X
            pointPath(pointPath.GetUpperBound(0)).Y = e.Y
            pointNum += 1
        ElseIf e.Button = MouseButtons.Right Then
            myGraph.DrawLines(myPen, pointPath)
            pointNum = 0
        End If

    End Sub

    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove

        If pointNum > 1 Then
            myGraph.Clear(PictureBox1.BackColor)
            myGraph.DrawLines(myPen, pointPath)
            myGraph.DrawLine(myPen, pointPath(pointNum - 1).X, pointPath(pointNum - 1).Y, e.X, e.Y)
        ElseIf pointNum = 1 Then
            myGraph.Clear(PictureBox1.BackColor)
            myGraph.DrawLine(myPen, pointPath(pointNum - 1).X, pointPath(pointNum - 1).Y, e.X, e.Y)
        End If
    End Sub
End Class