2010-06-17 58 views
1

我有下面的代码的边界:获取特定的窗口

System.Drawing.Rectangle desktop_Rectangle = System.Windows.Forms.Screen.PrimaryScreen.Bounds

这给了我桌面上的边界。

我现在正在寻找使用窗口标题来获取特定窗口的边界。

我是否必须使用Interop才能完成此操作?

任何示例代码将不胜感激。

谢谢

回答

4
namespace NativeInterop { 
    using System.Runtime.InteropServices; 

    public static partial class User32 { 
     private const string DLL_NAME = "user32.dll"; 

     [StructLayout(LayoutKind.Sequential)] 
     private struct RECT { 
      int left, top, right, bottom; 

      public Rectangle ToRectangle() { 
       return new Rectangle(left, top, right - left, bottom - top); 
      } 
     } 

     [DllImport(DLL_NAME, SetLastError = true)] 
     public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, String className, String windowTitle); 

     [DllImport(DLL_NAME)] 
     private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect); 

     public static Rectangle GetClientRect(IntPtr hWnd) { 
      var nativeRect = new RECT(); 
      GetClientRect(hWnd, out nativeRect); 
      return nativeRect.ToRectangle(); 
     } 
    } 
} 

用法:

var handle = User32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, String.Empty, "My Caption"); 
var rect = User32.GetClientRect(handle); 
+0

我不得不打电话FindWindowEx与空代替的String.Empty。当我调用GetClientRect()时,left和top(x和y)的值总是为0.任何想法是什么导致了这种情况? – Lars 2015-07-14 21:34:58