Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Setting mouse cursor position with WinAPI

DZone's Guide to

Setting mouse cursor position with WinAPI

·
Free Resource

Setting the mouse cursor position on a Windows machine with the help of .NET Framework shouldn't be that big of a problem. After all, there is the built-in Cursor class that lets you do that by executing a simple line of code:

Cursor.Position = new System.Drawing.Point(0, 0);

Of course, here 0 and 0 are the absolute coordinates for the mouse cursor on the screen. One thing to mention about this type of position setting is that Cursor requires a reference to System.Windows.Forms. And in some cases you don't want this extra reference. If that's the case, WinAPI is your solution. It requires some more work compared to the regular .NET way (class instance -> method call) but at the end you get more control than you would expect.

When using WinAPI to set the cursor position, there are two ways you can go:

mouse_event is the very basic function that is only able to set the mouse coordinates. It was superseded and Microsoft recomends using SendInput instead. Nonetheless, it still works (although I cannot say for sure whether it will be working in future releases of Windows).

So to start, I have a very basic class:

class WINAPI_SUPERSEDED
{
[DllImport("user32.dll",SetLastError=true)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

public enum MouseFlags
{
MOUSEEVENTF_ABSOLUTE = 0x8000,
MOUSEEVENTF_LEFTDOWN = 0x0002,
MOUSEEVENTF_LEFTUP = 0x0004,
MOUSEEVENTF_MIDDLEDOWN = 0x0020,
MOUSEEVENTF_MIDDLEUP = 0x0040,
MOUSEEVENTF_MOVE = 0x0001,
MOUSEEVENTF_RIGHTDOWN = 0x0008,
MOUSEEVENTF_RIGHTUP = 0x0010,
MOUSEEVENTF_WHEEL = 0x0800,
MOUSEEVENTF_XDOWN = 0x0080,
MOUSEEVENTF_XUP = 0x0100
}

public enum DataFlags
{
XBUTTON1 = 0x0001,
XBUTTON2 = 0x0002
}
}

So to set the cursor position to 0,0 I would use this:

WINAPI_SUPERSEDED.mouse_event((int)WINAPI_SUPERSEDED.MouseFlags.MOUSEEVENTF_MOVE | (int)WINAPI_SUPERSEDED.MouseFlags.MOUSEEVENTF_ABSOLUTE, 0, 0, 0, 0);

If you go through the documentation, you will notice that in fact, dx and dy are in no way direct coordinates but rather normalized values ranged between 0 and 65,535 - that is only when the MOUSEEVENTF_ABSOLUTE flag is present. Otherwise, the position will be adjusted according to the current mouse cursor position.

This method doesn't return any value so I cannot be informed whether it was successful or not. GetLastError won't give much information either. In this case, SendInput comes to the rescue.

Here is what I have defined as the main class:

class WINAPI
{
[DllImport("kernel32.dll")]
public static extern uint GetLastError();

public enum MouseData
{
XBUTTON1 = 0x0001,
XBUTTON2 = 0x0002
}

public enum MouseFlags
{
MOUSEEVENTF_ABSOLUTE = 0x8000,
MOUSEEVENTF_HWHEEL = 0x01000,
MOUSEEVENTF_MOVE = 0x0001,
MOUSEEVENTF_MOVE_NOCOALESCE = 0x2000,
MOUSEEVENTF_LEFTDOWN = 0x0002,
MOUSEEVENTF_LEFTUP = 0x0004,
MOUSEEVENTF_RIGHTDOWN = 0x0008,
MOUSEEVENTF_RIGHTUP = 0x0010,
MOUSEEVENTF_MIDDLEDOWN = 0x0020,
MOUSEEVENTF_MIDDLEUP = 0x0040,
MOUSEEVENTF_VIRTUALDESK = 0x4000,
MOUSEEVENTF_WHEEL = 0x0800,
MOUSEEVENTF_XDOWN = 0x0080,
MOUSEEVENTF_XUP = 0x0100
}

[DllImport("user32.dll", SetLastError=true)]
public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

[StructLayout (LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public int type;
[FieldOffset(4)]
public MOUSEINPUT mi;
}

public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public int extraInfo;
}
}

This class is a bit more complicated, but at the same time you have to understand that in some cases, SendInput is used for hardware and keyboard input as well. Of course, for experimentation purposes I removed those parts in the sample class.

Here you have the same MouseFlags enum that will let you pass custom flags defining the mouse behavior. Notice, that SendInput has SetLastError set to true, therefore if something wrong happens via this method, the error will be easily obtained via GetLastError, that is implemented as a helper method in the same class.

VERY IMPORTANT: When you define the INPUT struct, make sure you use LayoutKind.Explicit since when passed to an unamanaged call, a specific field layout is required - as you can see, every field is decorated with a FieldOffset attribute.

Also taking about StructLayout, you don't have to set StructLayout.Sequential to MOUSEINPUT since it is setautomatically by CLR.

When I want to call the method above, I can simply use this snippet:

WINAPI.MOUSEINPUT mouseInput = new WINAPI.MOUSEINPUT();
mouseInput.dx = 100;
mouseInput.dy = 10;
mouseInput.dwFlags = (int)WINAPI.MouseFlags.MOUSEEVENTF_ABSOLUTE | (int)WINAPI.MouseFlags.MOUSEEVENTF_MOVE;

WINAPI.INPUT input = new WINAPI.INPUT();
input.type = 0;
input.mi = mouseInput;

uint x = WINAPI.SendInput(1, ref input, Marshal.SizeOf(input));
Console.WriteLine(x);

Console.WriteLine(WINAPI.GetLastError());
Console.ReadLine();

Notice that I have to call the unmanaged version of sizeof and pass the INPUT struct to it in order for the method to correctly execute. The regular C# sizeof won't cut it here.

When I am defining the type of input, 0 is repesenting the INPUT_MOUSE flag, since I am only handling the mouse here.

Of course, I can re-organize my method to accept a set of INPUT instances - the native call itself allows this by requesting an array of INPUT and the correct indication of the number of INPUT instances passed, but that is not required for testing purposes.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}