笔记4:与事件的交互



鼠标点击、弹起、按下等,其中的参数e记录了鼠标的位置信息(e.X ,  e.Y)

可将其当作直线的起点或终点。






笔记4:与事件的交互_第1张图片

通过两次点击,画出对应的直线。

Imports System.Drawing

Public Class Form1
    Dim gr As Graphics
    Dim FirstClick As Boolean = False '是否为第一次点击
    Dim p1 As Point
    Dim p2 As Point

    '鼠标事件中记录了鼠标的位置(e.x,e.y)
    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        FirstClick = Not FirstClick
        gr = Me.CreateGraphics
        If FirstClick = True Then
            p1.X = e.X
            p1.Y = e.Y
            gr.DrawString(e.X & " " & e.Y, Me.Font, Brushes.Red, p1) '输出坐标
        Else
            p2.X = e.X
            p2.Y = e.Y
            gr.DrawString(e.X & " " & e.Y, Me.Font, Brushes.Red, p2)
            gr.DrawLine(Pens.Maroon, p1, p2)
        End If
    End Sub
End Class







笔记4:与事件的交互_第2张图片

通过连续点击,画连续的折线

Imports System.Drawing

Public Class Form1
    Dim gr As Graphics
    Dim FirstClick As Boolean = False
    Dim p1 As Point
    Dim p2 As Point

    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        If FirstClick = False Then
            p1.X = e.X
            p1.Y = e.Y
            FirstClick = True
        Else
            p2.X = e.X
            p2.Y = e.Y
            gr = Me.CreateGraphics
            gr.DrawLine(Pens.Red, p1, p2)
            p1 = p2
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Refresh() '清屏
        FirstClick = False
    End Sub
End Class







笔记4:与事件的交互_第3张图片

画任意曲线

通过鼠标按下、弹起作为标识,来画直线,不断替换起点和终点。

Imports System.Drawing

Public Class Form1
    Dim gr As Graphics
    Dim FirstClick As Boolean = False
    Dim p1 As Point
    Dim p2 As Point

    Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
        FirstClick = True
        p1.X = e.X
        p1.Y = e.Y
    End Sub

    Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
        FirstClick = False
    End Sub

    Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        If FirstClick = True Then
            p2.X = e.X
            p2.Y = e.Y

            gr = Me.CreateGraphics
            gr.DrawLine(Pens.Blue, p1, p2)
            p1 = p2
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Refresh() '清屏
        FirstClick = False
    End Sub
End Class





你可能感兴趣的:(事件,VB.NET,图形,交互)