- Home /
How do you move the mouse cursor with code?
I've tried using
[DllImport("user32.dll")]
public static extern bool SetCursorPos(float X, float Y);
but it always moves the mouse to the top left of the screen regardless of what I put for X and Y. Help pls
Answer by Eno-Khaon · Sep 13, 2021 at 10:37 PM
Looking at the PInvoke entry for User32.SetCursorPos(int, int), I would guess that you're running into problems due to data type incompatibility.
The function specifically uses integers, but you're feeding in floating point numbers, which have very different structure.
As an additional note, you'll need to make sure that the Cursor position you're getting from Unity to convert for SetCursorPos() follows the same bounds and rules, since Unity generally marks (0, 0) as a corner of the Unity game's window and isn't directly tied to the full screen like Windows would reference. Furthermore, a built Player and the Editor might have differing rules on exactly how values are presented to you for mouse position as well. Keep this in mind depending on how you're planning coordinate conversions.
Your answer
