VB.Net(WinForms)绘制一条线来跟随光标 [英] VB.Net (WinForms) Drawing a Line to Follow the Cursor

查看:252
本文介绍了VB.Net(WinForms)绘制一条线来跟随光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在线移动时将线绘制到光标当前位置。我尝试将下面的代码添加到表单中的 MouseMove 事件中;然而,没有任何改变。我已经能够成功画出线条,但无论我做什么,我都无法像追随鼠标一样。此外,如果能够使用可靠的代码而无需使用定时器(出于资源的原因),但无论什么作品,都可以实现这一点,这将是一件很好的事情。

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.

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

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

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

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.

推荐答案



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

这个表单实例。

使用 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

这篇关于VB.Net(WinForms)绘制一条线来跟随光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆