我试图在游标移动时将线条绘制到游标当前位置。我已尝试将以下代码添加到表单中的 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 事件的代码,但它失败了(我只是包括它,所以你可以看到之前的尝试)。提前感谢您的帮助。
答案 0 :(得分:2)
这将满足您的需求:
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
指的是Form
个实例。
使用http://converter.telerik.com/
将代码翻译为Vb.NetPrivate 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