How to tips and tricks for Microsoft Visual Studio .net

Thursday, June 10, 2010

Get mouse location on form no matter what

Someone asked me how to get the mouse location on a windows form no matter what controls are on the form.

A lot of suggestions were made about using the following...

Place a label on the form and use the following code in the Mouse Move event on the form.
   Private Sub Form1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
Label1.Text = Cursor.Position.ToString()
End Sub
While the code in the Mouse Move event handler will work, there will be a problem in that it will stop working as soon as the mouse moves over a control on the form. This is because the Mouse Move event of the control takes over. Your code is only in the Mouse Move even handler of the form.
To handle this you could create a Mouse Move even handler for every control on your form, and work out the position of the mouse on the form with some clever code.

I have to ask... What happens if you have many container controls all full of other controls. Do you really want to have to create a Mouse Move event handler for each one, and then have to work out if the control your cursor is moving over is within a container control?

My guess is no!

I have a much simpler solution...

Add a timer to your form, set the interval property to something like 10 milliseconds, and use the following in a Timer Tick event handler...

   Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 
Label1.Text = Me.PointToClient(Me.MousePosition).ToString()
End Sub
This will give you the position of the mouse cursor on the form, no matter what controls your cursor moves over.

No comments:

Post a Comment