是否有用于按窗口标题查找窗口句柄的托管 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;
}

有没有办法使用托管 API 创建依赖于字符串windowTitleHandleRef对象?

编辑:这是我最终得到的代码:

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;
}
System.Diagnostics.Process[] _procs = 
    System.Diagnostics.Process.GetCurrentProcess().GetProcesses();

将返回本地计算机上运行的所有进程。您可以遍历它们。

主窗口标题将显示在 Process.MainWindowTitle 属性上。

Process.Handle可能是你感兴趣的位。

最新更新