DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Evaluating Similariy Digests: A Study of TLSH, ssdeep, and sdhash Against Common File Modifications
  • Designing Fault-Tolerant Messaging Workflows Using State Machine Architecture
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer

Trending

  • The Missing Infrastructure Layer: Why AI's Next Evolution Requires Distributed Systems Thinking
  • Defining Effective Microservice Boundaries - A Practical Approach To Avoiding The Most Common Mistakes
  • Operationalizing Data Quality in Cloud ETL Workflows: Automated Validation and Anomaly Detection
  • Serverless IAM: Implementing IAM in Serverless Architectures with Lessons from the Security Trenches
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Setting mouse cursor position with WinAPI

Setting mouse cursor position with WinAPI

By 
Denzel D. user avatar
Denzel D.
·
Nov. 28, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
16.4K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • SendInput 

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.

Data structure Pass (software) .NET Snippet (programming) Release (computing) Documentation Machine

Opinions expressed by DZone contributors are their own.

Related

  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Evaluating Similariy Digests: A Study of TLSH, ssdeep, and sdhash Against Common File Modifications
  • Designing Fault-Tolerant Messaging Workflows Using State Machine Architecture
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: