VB.Net (WinForms)沿着光标绘制一条线



问题

我试图让线绘制到光标的当前位置,因为它移动。我已经尝试将下面的代码添加到MouseMove事件的形式;然而,一切都没有改变。我已经能够成功地画出这条线,但不管我怎么做,我似乎就是不能让这条线跟着鼠标走。此外,如果能够使用可靠的代码而不使用计时器(为了资源的缘故)来实现这一点,那就太好了,但是无论如何都可以工作。

<标题> 代码

程序只是一个空白表单。到目前为止,这是我得到的所有代码(这是所有的代码):

Public Class drawing
Public xpos = MousePosition.X
Public ypos = MousePosition.Y
Public Sub DrawLineFloat(ByVal e As PaintEventArgs)
    ' Create pen.
    Dim blackPen As New Pen(Color.Black, 2)
    ' Create coordinates of points that define line.
    Dim x1 As Single = xpos
    Dim y1 As Single = ypos
    Dim x2 As Single = 100
    Dim y2 As Single = 100
    ' Draw line to screen.
    e.Graphics.DrawLine(blackPen, x1, y1, x2, y2)
End Sub
Private Sub drawing_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    DrawLineFloat(e)
End Sub
End Class

正如您所看到的,我试图修改MouseMove事件的代码,但它失败了(我只是包括它,所以您可以看到之前的尝试)。谢谢你的帮助。

这将满足您的需求:

private Point? startPoint;
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    if (startPoint.HasValue)
    {
        Graphics g = e.Graphics;
        using (Pen p = new Pen(Color.Black, 2f))
        {
            g.DrawLine(p, startPoint.Value, new Point(100, 100));
        }
    }
}
protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    this.startPoint = e.Location;
    this.Invalidate();
}

thisForm实例。

代码翻译成Vb。Net使用http://converter.telerik.com/

Private startPoint As System.Nullable(Of Point)
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)
    If startPoint.HasValue Then
        Dim g As Graphics = e.Graphics
        Using p As New Pen(Color.Black, 2F)
            g.DrawLine(p, startPoint.Value, New Point(100, 100))
        End Using
    End If
End Sub
Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
    MyBase.OnMouseMove(e)
    Me.startPoint = e.Location
    Me.Invalidate()
End Sub

最新更新