« Get buried under the weight of VS 2005, faster than ever | Main | Visual Studio Team System - Magic Tests »

August 18, 2005

How to: Move the mouse pointer programmatically

Yes, moving the mouse pointer for the user is evil, but if you ever need to:

    Public Structure POINT
        Public x As Integer
        Public y As Integer
    End Structure

    Public Declare Function SetCursorPos Lib "user32" _
        (ByVal X As Integer, ByVal Y As Integer) As Long
    Public Declare Function ClientToScreen Lib "user32" _
        (ByVal hWnd As IntPtr, ByRef point As POINT) As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        Dim p As New POINT
        p.x = Button1.Left + (Button1.Width / 2)
        p.y = Button1.Top + (Button1.Height / 2)
        ClientToScreen(Me.Handle, p)
        SetCursorPos(p.x, p.y)

    End Sub

This will move the cursor to the center of Button1 on the form.  Enjoy

Posted on August 18, 2005 at 02:30 PM | Permalink

Comments

You gotta be kidding me. How about some context?

Posted by: Jeff Atwood | Aug 19, 2005 1:28:19 AM

How to use in C#:

1.) Create a Windows Form application
2.) Create a class as below:

public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);

[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
}

3.) Paste the following code in the button's clik eventhandler:

Win32.POINT p = new Win32.POINT();
p.x = button1.Left + (button1.Width / 2);
p.y = button1.Top + (button1.Height / 2);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

This will move the mouse pointer to the center of the button.

Now write you're handler to move the mouse around - Enjoy!

Posted by: CoZaDeveloper | Sep 19, 2005 8:42:58 AM

Just wanted to say a big thank you to Scott and CoZaDeveloper for starting me off on a very useful tool.

Posted by: YourMum | Oct 13, 2005 3:56:50 AM

you could theoretically produce the world's annual meat supply. And you could do it in a way that's better for the environment and human health. In the long term, this is a very feasible idea

Posted by: pandora jewelry | Dec 13, 2010 4:56:03 AM

The comments to this entry are closed.