当前位置:首页 > Windows程序 > 正文

C# 模拟鼠标(mouse

2021-03-29 Windows程序

想必有很多人在项目开发中可能遇见需要做模拟鼠标点击的小功能,很多人会在

百度过后采用mouse_event这个函数,不过我并不想讨论如何去使用mouse_event

函数怎么去使用,因为那没有多大意义。

[csharp] view plaincopy

static void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo)  

{  

    int x = dx, y = dy;  

    edit_position(dwFlags, dx, dy, ref x, ref y);   

    IntPtr hWndFromPoint = WindowFromPoint(x, y);  

    screen_to_client(hWndFromPoint, ref x, ref y);   

    send_message(hWndFromPoint, dwFlags, cButtons, x, y);  

}  

上述代码你发现了什么?如果你发现说明你知道了本文到底在写什么东东 说不定你

会有一些兴趣看下去,,不过想到我如今混那么凄惨 在工地上做干活 不过也还好。

鼠标点击目标时会向鼠标所点击目标窗口投递消息,根据鼠标的按键、状态不同会

投递不同的消息,一个完整的“鼠标左键单击”事件过程为“WM_LBUTTONDOWN + 

WM_LBUTTONUP”即鼠标“先左键按下 + 后左键抬起”,由于mouse_event可以模拟

鼠标点击过程而不是直接性一次完整的鼠标单击过程,所以同样存在“按下、抬起”

[csharp] view plaincopy

mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP | MOUSEEVENTF_MOVE, -450, 0, 1, 0);  

mouse_event在没有提供MOUSEEVENTF_MOVE量时光标不会移动到相对位置,

“光标相对位置=光标现行位置+新光标位置”如果提供量“MOUSEEVENTF_ABSOLUTE”

绝对位置,则会以“新光标位置”为准而不会添加“光标现行位置”

[csharp] view plaincopy

static void edit_position(int dwFlags, int dx, int dy, ref int x, ref int y)  

{  

    Point pos = MousePosition;  

    x = x + pos.X;  

    y = y + pos.Y;  

    if ((dwFlags | MOUSEEVENTF_ABSOLUTE) == dwFlags)  

        SetCursorPos(dx, dy);  

    if ((dwFlags | MOUSEEVENTF_MOVE) == dwFlags)  

        SetCursorPos(x, y);  

}  

edit_position函数主要用于对MOUSEEVENTF_MOVE于MOUSEEVENTF_ABSOLUTE

相对/绝对光标位置修改的一个支持

[csharp] view plaincopy

static void send_message(IntPtr hWnd, int dwFlags, int cButtons, int x, int y)  

{  

    if ((dwFlags | MOUSEEVENTF_LEFTDOWN) == dwFlags)  

        SendMessage(hWnd, WM_LBUTTONDOWN, cButtons, MakeDWord(x, y));  

    if ((dwFlags | MOUSEEVENTF_LEFTUP) == dwFlags)  

        SendMessage(hWnd, WM_LBUTTONUP, cButtons, MakeDWord(x, y));  

    if ((dwFlags | MOUSEEVENTF_RIGHTDOWN) == dwFlags)  

        SendMessage(hWnd, WM_RBUTTONDOWN, cButtons, MakeDWord(x, y));  

    if ((dwFlags | MOUSEEVENTF_RIGHTUP) == dwFlags)  

        SendMessage(hWnd, WM_RBUTTONUP, cButtons, MakeDWord(x, y));  

    if ((dwFlags | MOUSEEVENTF_MIDDLEDOWN) == dwFlags)  

        SendMessage(hWnd, WM_MBUTTONDOWN, cButtons, MakeDWord(x, y));  

    if ((dwFlags | MOUSEEVENTF_MIDDLEUP) == dwFlags)  

        SendMessage(hWnd, WM_MBUTTONUP, cButtons, MakeDWord(x, y));  

}  

send_message函数主要用于模拟鼠标点击的过程,上面我提到“先左键按下 + 后左键抬起”

在上面的代码中你会看的清楚的不得了,如果相反你可以去尝试一番会有什么后果 与其说

不如你们自己做更要来的快些。

[csharp] view plaincopy

static int MakeDWord(int low, int high)  

{  

    return low + (high * Abs(~ushort.MaxValue));  

}  

  

static int Abs(int value)  

{  

    return ((value >> 31) ^ value) - (value >> 31);  

}  

MakeDWord / 合并整数,函数主要是把两个short合并为一个int,分为low、high两部分

[csharp] view plaincopy

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69451.html