简体   繁体   English

C# winapi mouse_event

[英]C# winapi mouse_event

        static uint DOWN = 0x0002;
        static uint UP = 0x0004;    
        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo); 
        
        static void Click()
        {
            mouse_event(DOWN, 800, 800, 0, 0);
            Thread.Sleep(100);
            mouse_event(UP, 800, 800, 0, 0);
        }

Why it does not click on my coordinates 800 800, it clicks where my mouse is为什么它没有点击我的坐标 800 800,它点击了我的鼠标所在的位置

If you want to click specified point instead of relative movement, the MOUSEEVENTF_ABSOLUTE flag is required.如果要单击指定点而不是相对移动,则需要MOUSEEVENTF_ABSOLUTE标志。 And in order for making the movement from current position to target position, the MOUSEEVENTF_MOVE flag is required.为了从当前 position 移动到目标 position,需要MOUSEEVENTF_MOVE标志。

So the code will like this:所以代码会是这样的:

    static uint DOWN = 0x0002;
    static uint UP = 0x0004;
    static uint MOUSEEVENTF_ABSOLUTE = 0x8000;
    static uint MOUSEEVENTF_MOVE = 0x0001;
    [DllImport("user32.dll")]
    static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);

    static void Click()
    {
        mouse_event(DOWN | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, 800, 800, 0, 0);
        Thread.Sleep(100);
        mouse_event(UP | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, 800, 800, 0, 0);
    }

And note:并注意:

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535.如果指定MOUSEEVENTF_ABSOLUTE值,则dxdy包含0到 65,535 之间的归一化绝对坐标。 The event procedure maps these coordinates onto the display surface.事件过程将这些坐标映射到显示表面上。 Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.坐标(0,0)映射到显示表面的左上角, (65535,65535)映射到右下角。

So if you want to click the specified pixel of the screen you can convert absolute coordinate to screen pixel like this:因此,如果要单击屏幕的指定像素,可以将绝对坐标转换为屏幕像素,如下所示:

    static int SM_CXSCREEN = 0;
    static int SM_CYSCREEN = 1;

    [DllImport("user32.dll")]
    static extern int GetSystemMetrics(int nIndex);

    static void Click()
    {
        int sx = GetSystemMetrics(SM_CXSCREEN);
        int sy = GetSystemMetrics(SM_CYSCREEN);

        int x = 800 * 65536 / sx;
        int y = 800 * 65536 / sy;

        mouse_event(DOWN | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
        Thread.Sleep(100);
        mouse_event(UP | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
    }

Note mouse_event function has been superseded.注意mouse_event function 已被取代。 Use SendInput instead.请改用SendInput

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM