I tried to recreate a small thing I tried ages ago. It's literally just a simple paint program. The code is basically:
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
It works fine, the line draws from the main point to the next as the mouse moves. However, the accuracy of the drawn line is questionable. When drawing in the regular window size (586, 634) on my second monitor (Running at 1280x720) the line very closely follows the mouse tip (but isn't exact). But when the window is on my main (1920x1080) screen, the line is WAY off. Is there a specific reason for this, because I thought calling Control.MousePosition.X/Y got the mouse's position in relation to the window's size not the screen size? (Or something else)
I'm usually able to figure these things out on my own, but this just seems wrong in general. Any ideas?
From MSDN:
The MousePosition property returns a Point that represents the mouse cursor position at the time the property was referenced. The coordinates indicate the position on the screen, not relative to the control, and are returned regardless of whether the cursor is positioned over the control. The coordinates of the upper-left corner of the screen are 0,0.
You are getting the position of the mouse relative to the screen instead of to the control that raised the mouse event.
For the latter you should use the MouseEventArgs
variable e
, and specifically its Location
property.
That way you get the position relative to your form instead of the screen.
E.g.
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
So it is not a problem with an inaccuracy of the drawn line, but of the coordinates to provide to the DrawLine
method. In your code you can notice that the offset shifts with the position of your form on the screen.