First, you have to understand that there's multiple coordinate systems at play here. The first coordinate system is called
screen coordinates. In this coordinate system, (0, 0) is located at the top left corner of your primary monitor. Positive x is to the right, positive y is down. The second coordinate system is called
client coordinates. In this coordinate system, (0, 0) is located at the top left corner of a control, with the same axis direction as screen coordinates (barring any transforms). Any control can translate a point from one system to the other by using its
PointToScreen or
PointToClient methods.
If you handle a control's
MouseUp or
MouseDown event, you will receive a
MouseEventArgs as a parameter. This has a
Location property, along with
X and
Y to tell you where the mouse was when the event was generated. Unfortunately, it is not documented whether these coordinates are in client coordinates or screen coordinates; you should be able to determine quickly with a test application.
The
Click event only provides an
EventArgs parameter, which doesn't have any cursor location information. In this case, you use the
System.Windows.Forms.Cursor class to find the location. It's
Position property gives you the mouse position in screen coordinates.
Here's a form that demonstrates the more cumbersome
Cursor.Position method:
Code:
Public Class DemoForm
Inherits Form
Dim _picBox As PictureBox
Public Sub New()
_picBox = New PictureBox()
_picBox.BackColor = Color.DarkGreen
_picBox.Location = New Point(0, 0) ' client coordinates relative to the form
_picBox.Dock = DockStyle.Fill
AddHandler _picBox.Click, AddressOf PicBoxOnClick
Me.Padding = New Padding(25)
Me.StartPosition = FormStartPosition.CenterScreen
Me.Controls.Add(_picBox)
End Sub
Private Sub PicBoxOnClick(ByVal sender As Object, ByVal e As EventArgs)
Dim screenLocation As Point = Cursor.Position
Dim clientLocation As Point = _picBox.PointToClient(screenLocation)
MessageBox.Show(clientLocation.ToString())
End Sub
End Class
Personally, I prefer using
MouseUp to take advantage of the convenient
MouseEventArgs, which in this case seems to use client coordinates:
Code:
Public Class DemoForm
Inherits Form
Dim _picBox As PictureBox
Public Sub New()
_picBox = New PictureBox()
_picBox.BackColor = Color.DarkGreen
_picBox.Location = New Point(0, 0) ' client coordinates relative to the form
_picBox.Dock = DockStyle.Fill
AddHandler _picBox.MouseUp, AddressOf PicBoxOnMouseUp
Me.Padding = New Padding(25)
Me.StartPosition = FormStartPosition.CenterScreen
Me.Controls.Add(_picBox)
End Sub
Private Sub PicBoxOnMouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
MessageBox.Show(e.Location.ToString())
End Sub
End Class