This is a mirror of official site: http://jasper-net.blogspot.com/

Setting mouse cursor position with WinAPI

| Tuesday, November 30, 2010
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,


Read more: .NET Zone

Posted via email from .NET Info

0 comments: