Get a Screenshot of a Specific Application

Get a screenshot of a specific application

Here's some code to get you started:

public void CaptureApplication(string procName)
{
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);
using (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);
}

It works, but needs improvement:

  • You may want to use a different mechanism to get the process handle (or at least do some defensive coding)
  • If your target window isn't in the foreground, you'll end up with a screenshot that's the right size/position, but will just be filled with whatever is in the foreground (you probably want to pull the given window into the foreground first)
  • You probably want to do something other than just save the bmp to a temp directory

How to screenshot a specific application using dart?

Using this code I could get a screenshot of a whole screen

That is not really what the code you've shown does. That code is instructing a Flutter renderer in your application to render something to an image. Having your own application draw some or all of its UI to an image instead of the screen is completely different from getting a screenshot; the latter involves asking the OS for the output of everything that is rendering to the screen, post OS-level composition. On mobile, where applications are generally full screen, those things might have similar output, but they are not at all the same thing.

There is no Dart API that will take an actual screenshot. You would have to write native code that uses native OS APIs to take screenshots on each desktop OS you want to support, and call that code via FFI (or, if you are using Flutter as in your example code, you could use platform channels).

Taking Screenshot of a Particular Application

Change

IntPtr h = p.Handle;

to

IntPtr h = p.MainWindowHandle;

and check.



Related Topics



Leave a reply



Submit