加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#使用win32api实现获取光标位置

发布时间:2020-12-15 03:46:55 所属栏目:百科 来源:网络整理
导读:方法一:需要调用win32api,winform、wpf通用 [DllImport("user32.dll")]public static extern bool GetCursorPos(out POINT lpPoint); [StructLayout(LayoutKind.Sequential)]public struct POINT{ public int X; public int Y; public POINT(int x,int y)

方法一:需要调用win32api,winform、wpf通用

[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
 
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
  public int X;
  public int Y;
  public POINT(int x,int y)
  {
    this.X = x;
    this.Y = y;
  }
}

方法二:通过调用Win32 API设置鼠标位置,实现移到指定位置,模仿并实现鼠标点击动作,并回到鼠标原先位置的方法,代码如下:

//获取屏幕
      int width = (int)SystemParameters.PrimaryScreenWidth;//得到屏幕整体宽度
      int height = (int)SystemParameters.PrimaryScreenHeight;//得到屏幕整体高度
//获取鼠标初始位置,相对屏幕的绝对位置
      System.Drawing.Point p = new System.Drawing.Point();

      ApiHelper.GetCursorPos(out p);
      if (width != 0) p.X = 65535 * p.X / width;
      if (height != 0) p.Y = 65535 * p.Y / height;
//设置移动的位置坐标
      int dy = 100;
      int dx = 100;
      dx = (int)(dx * 65535 / width);
      dy = (int)(dy * 65535 / height);
           
//移到指定位置 

ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_MOVE | MouseEventFlag.MOUSEEVENTF_ABSOLUTE),dx,dy,IntPtr.Zero);//移动到需要点击的位置
    
//完成一次点击
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTDOWN),IntPtr.Zero);
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTUP),IntPtr.Zero);//
//单击可以写为
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTDOWN | MouseEventFlag.MOUSEEVENTF_LEFTUP),IntPtr.Zero);
//双击则再重复单击方法
 
//回到初始位置
 ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_MOVE | MouseEventFlag.MOUSEEVENTF_ABSOLUTE),p.X,p.Y,IntPtr.Zero);//移动到需要点击的位置

代码中ApiHelper为作者封装的Win32 API方法,读者可以通过api精灵等软件查询api函数,自行实现封装。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读