Jerry Nixon
Jerry Nixon

Reputation: 31813

Can you force the Mouse to move?

If I know an X and Y coordinate, is there a Windows API or some technique in .Net that I can use to cause the mouse pointer to move to that point?

I know there must be something because there are tools that seem to jump the mouse. But I don't know if those APIs are easily accessible in .Net. Is there?

Please assume WPF, .Net, and Windows (of course).

Solution

public Window1()  
{  
    InitializeComponent();  
    NativeMethods.SetCursorPos(300, 300);  
}  
public partial class NativeMethods  
{  
    [System.Runtime.InteropServices.DllImportAttribute("user32.dll", 
        EntryPoint = "SetCursorPos")]  
    [return: System.Runtime.InteropServices.MarshalAsAttribute
        (System.Runtime.InteropServices.UnmanagedType.Bool)]  
    public static extern bool SetCursorPos(int X, int Y);  
} 

Upvotes: 3

Views: 1065

Answers (3)

Lenar
Lenar

Reputation: 398

Declare import like this:

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

And use like this:

SetCursorPos(x, y);

Upvotes: 2

Derek Park
Derek Park

Reputation: 46846

Are you opposed to using P/Invoke? If not, this is a pretty simple API to pull in.

http://pinvoke.net/default.aspx/user32/SetCursorPos.html

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

Upvotes: 0

Dror
Dror

Reputation: 2588

You can call WIN32 API methods.

Here's an example -

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6be8299a-9616-43f4-a72f-799da1193889/

Upvotes: 0

Related Questions