How to Set mouse cursor position to a specified point on screen in C#?

前端 未结 2 928
眼角桃花
眼角桃花 2020-12-11 07:48

How to Set mouse cursor position to a specified point on screen in C#?

am i must hacke the motherboard buffer that receive the mouse and keyboard coordinates and pre

2条回答
  •  心在旅途
    2020-12-11 08:44

    The following will set the mouse position and perform a click:

    public static void ClickSomePoint() {
        // Set the cursor position
        System.Windows.Forms.Cursor.Position = new Point(20, 35);
    
        DoClickMouse(0x2); // Left mouse button down
        DoClickMouse(0x4); // Left mouse button up
    }   
    
    static void DoClickMouse(int mouseButton) {
        var input = new INPUT() {
            dwType = 0, // Mouse input
            mi = new MOUSEINPUT() { dwFlags = mouseButton }
        };
    
        if (SendInput(1, input, Marshal.SizeOf(input)) == 0) { 
            throw new Exception();
        }
    }
    [StructLayout(LayoutKind.Sequential)]
    struct MOUSEINPUT {
        int dx;
        int dy;
        int mouseData;
        public int dwFlags;
        int time;
        IntPtr dwExtraInfo;
    }   
    struct INPUT {
        public uint dwType;
        public MOUSEINPUT mi;
    }   
    [DllImport("user32.dll", SetLastError=true)]
    static extern uint SendInput(uint cInputs, INPUT input, int size);
    

    Just keep in mind that this could be extremely annoying for a user.

    :)


    If you want to click a button on your form you can use the 'PerformClick()' method.

提交回复
热议问题