2013-12-20 58 views
0

這是我目前使用的代碼:是否有託管API用於通過窗口標題查找窗口句柄?

private Bitmap getScreenshotOfWindow(String windowTitle) { 
    RECT win32Rect; 
    HandleRef handle = new HandleRef(this, Handle); 

    if (!GetWindowRect(handle, out win32Rect)) { 
     MessageBox.Show(@"Error: unable to get window boundaries."); 
     return null; 
    } 

    Rectangle bounds = new Rectangle(); 
    bounds.X = win32Rect.Left; 
    bounds.Y = win32Rect.Top; 
    bounds.Width = win32Rect.Right - win32Rect.Left + 1; 
    bounds.Height = win32Rect.Bottom - win32Rect.Top + 1; 

    Bitmap screenshot = new Bitmap(bounds.Width, bounds.Height); 
    using(Graphics g = Graphics.FromImage(screenshot)) { 
     g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); 
    } 
    return screenshot; 
} 

有什麼辦法來創建一個HandleRef對象,取決於使用管理API的字符串windowTitle

編輯:這是我結束了代碼:

private Bitmap getScreenshotOfWindow(String windowTitle) { 
    RECT win32Rect; 
    IntPtr handle = getWindowHandle(windowTitle); 

    if (handle == IntPtr.Zero) { 
     MessageBox.Show(@"Error: Unable to find window."); 
     return null; 
    } 

    if (!GetWindowRect(handle, out win32Rect)) { 
     MessageBox.Show(@"Error: unable to get window boundaries."); 
     return null; 
    } 

    Rectangle bounds = new Rectangle(); 
    bounds.X = win32Rect.Left; 
    bounds.Y = win32Rect.Top; 
    bounds.Width = win32Rect.Right - win32Rect.Left + 1; 
    bounds.Height = win32Rect.Bottom - win32Rect.Top + 1; 

    Bitmap screenshot = new Bitmap(bounds.Width, bounds.Height); 
    using(Graphics g = Graphics.FromImage(screenshot)) { 
     g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); 
    } 
    return screenshot; 
} 

private IntPtr getWindowHandle(string windowTitle) { 
    foreach (Process proc in Process.GetProcesses()) { 
     if (proc.MainWindowTitle.Equals(windowTitle)) { 
      return proc.MainWindowHandle; 
     } 
    } 

    return IntPtr.Zero; 
} 
+0

表單具有句柄proeprty,但如果您無法訪問項目中的表單,則必須使用我知道的winapi。 http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(v=vs.110).aspx –

+0

您需要包裝FindWindow本機API。這很容易;見Pinvoke.net – EricLaw

回答

1
System.Diagnostics.Process[] _procs = 
    System.Diagnostics.Process.GetCurrentProcess().GetProcesses(); 

將返回本地計算機上運行的所有進程。你可以遍歷它們。

主窗口標題將出現在Process.MainWindowTitle屬性中。

Process.Handle可能是你感興趣的一點。