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;
}
表單具有句柄proeprty,但如果您無法訪問項目中的表單,則必須使用我知道的winapi。 http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(v=vs.110).aspx –
您需要包裝FindWindow本機API。這很容易;見Pinvoke.net – EricLaw