Take a screenshot in the process window

I am trying to take a screenshot in a process window on a 64-bit version of Windows 7, the problem is that I always get an error in the following line:

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

Saying "invalid parameters", I made a throw to see the errors, and the width and height are always 0.

Previously, in 32 bits this worked fine, but now in 64 bits it no longer works.

Code:

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);
}

How to fix this error?

+6
source share
1 answer

Getting a firefox process returns an array of processes, and you're looking for one that has a realistic-sized rectangle, which is the main process.

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;
    }
}
+2
source

All Articles