【问题标题】:How to get cursor pos in a specific windows?如何在特定窗口中获取光标位置?
【发布时间】:2021-04-13 01:07:05
【问题描述】:

我正在寻找在特定窗口中的光标位置。 目前,我明白了:

        /// <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++ 这样的窗口。

【问题讨论】:

标签: c# pinvoke user32


【解决方案1】:

这里是任何想要像我一样做的人的解决方案
感谢@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);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2020-06-24
    • 1970-01-01
    • 2018-10-26
    • 2021-07-09
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多