2010-06-17 97 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