Recipe 14.18. Moving the (Mouse) Cursor


Problem

You want to reposition the cursor (that is, the mouse pointer) programatically.

Solution

Sample code folder: Chapter 14\MoveMouse

Modify the Position property of the System.Windows.Forms. Cursor object with a new System.Drawing.Point containing the new location.

Discussion

Create a new Windows Forms project, and add two Button controls named Button1 and Button2. Now add the following code to the form's class:

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click    Windows.Forms.Cursor.Position = New Point( _       Me.PointToScreen(Button2.Location).X + _       Button2.Width / 2, _       Me.PointToScreen(Button2.Location).Y + _       Button2.Height / 2) End Sub 

When you run the program and click on Button1, the cursor centers itself over Button2.

All controls on a form use the client coordinate system for their positions. Each control's X and Y locations are based on the upper-left corner of the form's client area, the rectangle that is just inside of the form's border. The cursor, however, is a screen-wide resource, and it uses the coordinates for the entire screen, with its X and Y positions offset from the upper-left corner of the screen. To move the cursor based on a screen position, you must translate between the two coordinate systems.

The form includes two methods to perform this translation: PointToScreen(), which converts a client rectangle location to a matching screen location, and PointToClient(), which translates in the opposite direction. Actually, every control on the form also includes these two methods. However, all points translated using a control's translation methods are based on the upper-left corner of the control (that is, on its client area), and not on the upper-left corner of the form's client rectangle.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net