在流程窗口中截取屏幕截图

时间:2017-10-26 14:28:46

标签: c#

我试图在Windows 7 64位的进程窗口中截屏,问题是我总是在以下行中出错:

var bmp = new Bitmap (width, height, PixelFormat.Format32bppArgb);

说“无效参数”,我做了一个看到错误,宽度和高度始终为0。

在32位之前它运行良好,但现在64位不再起作用。

代码:

public void CaptureApplication()
{
    string procName = "firefox";

    var proc = Process.GetProcessesByName(procName)[0];
    var rect = new User32.Rect();
    User32.GetWindowRect(proc.MainWindowHandle, ref rect);

    int width = rect.right - rect.left;
    int height = rect.bottom - rect.top;

    var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
    Graphics graphics = Graphics.FromImage(bmp);
    graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);

    bmp.Save("c:\\tmp\\test.png", ImageFormat.Png);
}

private class User32
{
    [StructLayout(LayoutKind.Sequential)]
    public struct Rect
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
}

如何解决此错误?

1 个答案:

答案 0 :(得分:2)

获取firefox的进程会返回一个进程数组,您正在寻找一个具有实际大小的矩形的进程,这是一个主要的进程。

Process[] procs = Process.GetProcessesByName(procName);
var rect = new User32.Rect();
int width = 0;
int height = 0:
foreach (Process proc in procs)
{
    User32.GetWindowRect(proc.MainWindowHandle, ref rect);
    width = rect.right - rect.left;
    height = rect.bottom - rect.top;
    // break foreach if an realistic rectangle found => main process found
    if (width != 0 && height != 0)
    {
        break;
    }
}