我试图重新创造一个我很久以前尝试过的小东西。它实际上只是一个简单的绘画程序。代码基本上是:
Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
X = Control.MousePosition.X
Y = Control.MousePosition.Y
Mdown = True
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
Dim g As Graphics = Me.CreateGraphics
Dim NX As Integer = Control.MousePosition.X
Dim NY As Integer = Control.MousePosition.Y
If Mdown = True Then
g.DrawLine(System.Drawing.Pens.Red, X, Y, NX, NY)
X = NX
Y = NY
End If
End Sub
Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
Mdown = False
End Sub
它工作正常,当鼠标移动时,线从主点绘制到下一个点。但是,绘制线的准确性值得怀疑。当我在第二台显示器(在1280x720上运行)上绘制常规窗口大小(586,634)时,该线非常紧密地跟随鼠标尖端(但并不完全正确)。但是当窗口在我的主屏幕(1920x1080)屏幕上时,该线路是关闭的。是否有一个特定的原因,因为我认为调用Control.MousePosition.X / Y获得鼠标相对于窗口大小而不是屏幕大小的位置? (或其他东西)
我通常能够自己解决这些问题,但这似乎总的来说是错误的。有什么想法吗?
答案 0 :(得分:0)
来自MSDN:
MousePosition属性返回表示鼠标的Point 引用属性时的光标位置。坐标指示屏幕上的位置,而不是相对于控件,并且是 无论光标是否位于控件上,都会返回。该 屏幕左上角的坐标为0,0。
您将获得鼠标相对于屏幕的位置,而不是引发鼠标事件的控件。
对于后者,您应该使用dotfiles
变量MouseEventArgs
,特别是e
属性。
通过这种方式,您可以获得相对于表单而非屏幕的位置。
E.g。
Location
因此,绘制线的不准确性,以及提供给Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
X = e.X 'Equal to X = e.Location.X
Y = e.Y 'Equal to Y = e.Location.Y
Mdown = True
End Sub
方法的坐标不是问题。在您的代码中,您可以注意到偏移量随着表单在屏幕上的位置而变化。
答案 1 :(得分:0)
使用CreateGraphics()
绘图时,绘图临时(最小化/恢复应用并查看会发生什么)。要使图表持久,请将信息存储在GraphicsPath中,然后通过 Paint()中的e.Graphics
将图片呈现给您表格事件:
Public Class Form1
Private pt1 As Point
Private curGP As Drawing2D.GraphicsPath
Private GPs As New List(Of Drawing2D.GraphicsPath)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.DoubleBuffered = True
End Sub
Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
If e.Button = MouseButtons.Left Then
curGP = New Drawing2D.GraphicsPath
GPs.Add(curGP)
pt1 = New Point(e.X, e.Y)
End If
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
If e.Button = MouseButtons.Left Then
Dim pt2 As New Point(e.X, e.Y)
curGP.AddLine(pt1, pt2)
pt1 = pt2
Me.Invalidate()
End If
End Sub
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
For Each GP As Drawing2D.GraphicsPath In GPs
e.Graphics.DrawPath(Pens.Red, GP)
Next
End Sub
End Class