如何在另一个应用程序中获取光标位置

How to get cursor position within another app

我正在使用 .Net c# winforms。我想将鼠标移到另一个应用程序上,并在将鼠标移到它的界面上时查看光标 X、Y 位置。在我的表单标题栏上显示 X、Y 是可以的。我想查看此应用程序表单上特定位置的 X、Y 位置。

我想这样做的原因是因为这个应用程序的界面上有一些控件,我可以通过鼠标单击来转动旋钮,每次旋钮转动一次鼠标单击。我想编写一个应用程序,我可以将鼠标光标定位到此应用程序表单上的特定 X、Y 位置,然后单击软件鼠标将同一旋钮转动一圈。但我想通过我的应用程序执行此操作,我想你可以说有点像远程控制。当您位于正确的 X、Y 位置上时,其他应用程序旋钮会响应鼠标点击。

感谢任何正确方向的指点。

向您的表单添加标签并连接其 MouseMove() 和 QueryContinueDrag() 事件。使用 WindowFromPoint() 和 GetAncestor() API 获取包含光标位置的主 window 句柄,然后使用 ScreenToClient() API 将屏幕坐标转换为该表格的客户坐标。 运行 应用程序,然后向左将表单中的标签拖到目标应用程序中的旋钮上。标题栏应更新为当前鼠标位置相对于它所在的应用程序的客户端坐标:

    private const uint GA_ROOT = 2;

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr WindowFromPoint(int xPoint, int yPoint);

    [System.Runtime.InteropServices.DllImport("user32.dll", ExactSpelling = true)]
    private static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);

    private void label1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            label1.DoDragDrop(label1, DragDropEffects.Copy);
        }
    }

    private void label1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
    {
        Point pt = Cursor.Position;
        IntPtr wnd = WindowFromPoint(pt.X, pt.Y);
        IntPtr mainWnd = GetAncestor(wnd, GA_ROOT);
        POINT PT;
        PT.X = pt.X;
        PT.Y = pt.Y;
        ScreenToClient(mainWnd, ref PT);
        this.Text = String.Format("({0}, {1})", PT.X.ToString(), PT.Y.ToString());
    }