VB.Net (WinForms) Drawing a Line to Follow the Cur

2019-06-11 03:31发布

问题:

The Problem

I am trying to have the line draw to the cursors current position as it moves. I've tried adding the code below to the MouseMove event in the form; however, nothing changed. I have been able to successfully draw the line, but regardless of what I do I just can't seem to get the line to follow the mouse. Also, it would be nice to be able to achieve this with reliable code without using a timer (for resources sake), but whatever works, works.

Code

The program is simply a blank form. So far this is all I got for code (this is all of the code):

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

As you can see, I tried to modify the code for the MouseMove event, but it failed (I'm just including it anyways so you can see the previous attempt). Thanks in advance for any help.

回答1:

This will do what you need:

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();
}

this refers to the Form instance.

Code translated to Vb.Net using 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