Change cursor position using SendInput

The dx, dy in MOUSEINPUT should be within [0, 65535] when using absolute coordinates.

And the currect formula should be:

dx := x * 65536 / ScreenWidth + 1

Full code:

INPUT[] inputs = new INPUT[1];
inputs[0] = new INPUT
            {
                type = INPUTTYPE.INPUT_MOUSE,
                mi = new MOUSEINPUT()
                {
                    dx = x * 65536 / ScreenWidth + 1;,
                    dy = y * 65536 / ScreenHeight + 1,
                    mouseData = 0,
                    dwFlags = (uint)(MOUSEEVENTF.MOVE | MOUSEEVENTF.ABSOLUTE/* | MOUSEEVENTF.VIRTUALDESK*/),
                    time = 0,
                    dwExtraInfo = IntPtr.Zero
                }
            };
if (SendInput(1, inputs, Marshal.SizeOf(typeof(INPUT))) == 0)
    throw new Win32Exception(Marshal.GetLastWin32Error());

Further Reading

  1. MOUSEINPUT structure | Microsoft Docs
  2. AutoHotkey_L keyboard_mouse.cpp | GitHub

Posted:

Comments