Skip to main content
 首页 » 编程设计

c#之ClientToScreen 意外的返回值

2024年02月05日10arxive

我以前从未使用过 Windows。我付出了很多努力来获得正确的 X 和 Y 坐标和窗口大小,以及窗口客户区的大小。

不幸的是,客户区的 X 和 Y 始终为零。我在文档中查找它,它应该为零。

在 SO 上,我发现我需要将客户端传递给 ClientToScreen() 以使其与屏幕坐标相协调。然而,结果并不是我所期望的那样。

我得到的不是 Point(50,50)(或类似的),而是 Point(1,57027688545264E-312, 0)。

谁能告诉我哪里出了问题?

到目前为止,这是我的代码:

    [DllImport("user32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    static extern bool GetClientRect(IntPtr hWnd, out Rect rect); 
 
    [DllImport("user32.dll")] 
    static extern bool ClientToScreen(IntPtr hWnd, ref System.Windows.Point lpPoint); 
 
    [StructLayout(LayoutKind.Sequential)] 
    public struct Rect 
    { 
        public int Left; 
        public int Top; 
        public int Right; 
        public int Bottom; 
    } 
 
    static Rectangle GetClientRect(IntPtr handle) 
    { 
        Rect rect; 
        GetClientRect(handle, out rect); 
        System.Windows.Point p = new System.Windows.Point(0, 0); 
        ClientToScreen(handle, ref p); 
        rect.Left = (int)p.X; 
        rect.Top = (int)p.Y; 
        return new Rectangle(rect.Left, rect.Top, rect.Right, rect.Bottom); 
    } 

请您参考如下方法:

System.Windows.Point 结构与 ClientToScreen 不兼容。您应该改用 System.Drawing.Point。