找到窗口高度和宽度

如何找到聚焦窗口高度和宽度..

它可能是任何Windows窗口,如记事本,mspaint等…我可以借助此代码获得焦点窗口

[DllImport("user32")] public static extern IntPtr GetForegroundWindow(); 

嗨f3lix它正在工作,但它的返回值只取决于位置..如果我改变位置它返回一些其他值

Kunal它的返回错误信息….就像没有设置对象参考

我认为你必须通过PInvoke使用user32.dll函数。 我不确定,但我会这样做:

 [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] static extern bool GetWindowRect(IntPtr hWnd, out Rectangle lpRect); Rectangle rect = new Rectangle(); GetWindowRect(GetForegroundWindow(), out rect); 

注意:我没有尝试此代码,因为我目前不在Windows上工作…

编辑 : Rory向我指出(见注释)我们不能在这里使用标准的Rectangle,我们需要定义自己的RECT。

 [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } 

不要忘记在第一段代码中用RECT替换Rectangle

 [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); public static Size GetControlSize(IntPtr hWnd) { RECT pRect; Size cSize = new Size(); // get coordinates relative to window GetWindowRect(hWnd, out pRect); cSize.Width = pRect.Right - pRect.Left; cSize.Height = pRect.Bottom - pRect.Top; return cSize; } 

你的问题究竟是什么?

  1. 如何获得焦点窗口?
  2. 如何获得窗口的宽度和高度?

如果问题2,请使用Window.ActualWidthWindow.ActualHeight

如果你的窗口在你的应用程序中,有一个MDI应用程序,你可以使用它,有

 public static extern IntPtr GetForegroundWindow(); 

和你一起试试吧

 int wHeight = Control.FromHandle(GetForegroundWindow()).Height; int wWidth = Control.FromHandle(GetForegroundWindow()).Width; 

如果您正在构建MDI应用程序,则可以使用:

 parentForm.ActiveMDIChild.Size