using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace WQ
{
/// <summary>
/// 鼠标
/// </summary>
public class Mouse
{
// https://blog.youkuaiyun.com/fuhanghang/article/details/118700282
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
private const int MOUSEEVENTF_MOVE = 0x0001; // 移动鼠标
private const int MOUSEEVENTF_LEFTDOWN = 0x0002; // 鼠标左键按下
private const int MOUSEEVENTF_LEFTUP = 0x0004; // 鼠标左键抬起
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; // 鼠标右键按下
private const int MOUSEEVENTF_RIGHTUP = 0x0010; // 鼠标右键抬起
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; // 鼠标中键按下
private const int MOUSEEVENTF_MIDDLEUP = 0x0040; // 鼠标中键抬起
private const int MOUSEEVENTF_WHEEL = 0x0800; // 滑动鼠标滚轮
private const int MOUSEEVENTF_ABSOLUTE = 0x8000; // 绝对坐标
[DllImport("user32.dll")]
private extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
// https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-setcursorpos?redirectedfrom=MSDN
/// <summary>
/// 将光标移动到指定的屏幕坐标。
/// </summary>
/// <param name="X">屏幕坐标</param>
/// <param name="Y">屏幕坐标</param>
/// <returns>如果成功,则返回非零;否则返回零。</returns>
[DllImport("user32.dll")]
public extern static int SetCursorPos(int X, int Y);
// https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-getcursorpos?redirectedfrom=MSDN
/// <summary>
/// 定义一个屏幕坐标。
/// </summary>
public struct POINT
{
public int X;
public int Y;
}
/// <summary>
/// 获取光标的屏幕坐标。
/// </summary>
/// <param name="lpPoint">屏幕坐标</param>
/// <returns>如果成功,则返回非零;否则返回零。</returns>
[DllImport("user32.dll")]
public extern static int GetCursorPos(ref POINT lpPoint);
/// <summary>
/// 鼠标左键单击
/// </summary>
/// <param name="x">屏幕坐标</param>
/// <param name="y">屏幕坐标</param>
public static void Button_Left_Click(int x, int y)
{
SetCursorPos(x, y);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
/// <summary>
/// 鼠标左键双击
/// </summary>
/// <param name="x">屏幕坐标</param>
/// <param name="y">屏幕坐标</param>
public static void Button_Left_DoubleClick(int x, int y)
{
SetCursorPos(x, y);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
/// <summary>
/// 滑动滚轮
/// </summary>
/// <param name="x">屏幕坐标</param>
/// <param name="y">屏幕坐标</param>
/// <param name="number">滚轮移动量。正值表示滚轮向前旋转,远离用户;负值表示轮子向后旋转,朝向用户。一次滚轮点击被定义为WHEEL_DELTA,值为120。</param>
public static void Wheel(int x, int y, int number)
{
SetCursorPos(x, y);
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, number, 0);
}
}
}
C#鼠标控制
于 2023-02-16 22:17:24 首次发布