如何在特定窗口中获取光标位置?

问题描述

我希望在特定窗口中获得我的光标位置。 目前,我明白了:

        /// <summary>
        /// Struct representing a point.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public static implicit operator Point(POINT point) {
                return new Point(point.X,point.Y);
            }
        }

        /// <summary>
        /// Retrieves the cursor's position,in screen coordinates.
        /// </summary>
        /// <see>See MSDN documentation for further information.</see>
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out POINT lpPoint);

        public static Point GetCursorPosition() {
            POINT lpPoint;
            GetCursorPos(out lpPoint);
            // NOTE: If you need error handling
            // bool success = GetCursorPos(out lpPoint);
            // if (!success)

            return lpPoint;
        }

这项工作完美,但它并不特定于像 Spy++ 这样的窗口。

解决方法

这里是任何想像我一样做的人的解决方案
感谢@Simon Mourrier

        /// <summary>
        /// Struct representing a point.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public static implicit operator Point(POINT point) {
                return new Point(point.X,point.Y);
            }
        }

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

        /// <summary>
        /// Retrieves the cursor's position,in screen coordinates.
        /// </summary>
        /// <see>See MSDN documentation for further information.</see>
        [DllImport("user32.dll")]
        static extern bool GetCursorPos(out POINT lpPoint);

        public void GetCursorPosition() {
            POINT lpPoint;
            GetCursorPos(out lpPoint);
            ScreenToClient(process.MainWindowHandle,ref lpPoint);
            Console.WriteLine("X : " + lpPoint.X);
            Console.WriteLine("Y : " + lpPoint.Y);
        }