Search code examples
dartoperating-systemscreenshot

How to screenshot a specific application using dart?


Using this code I could get a screenshot of a whole screen, but how do I get a screenshot of a specific application using dart on a desktop operating system?? (https://stackoverflow.com/questions/51117958/how-to-take-a-screenshot-of-the-current-widget-flutter#:~:text=To%20take%20a%20screenshot%20of%20your%20widget%2C%20make,app%20folder%2C%20and%20run%20your%20widget%2C%20like%20this%3A - not really a whole either, at least not on a desktop operating system)

RenderRepaintBoundary boundary = previewContainer.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
final directory = (await getApplicationDocumentsDirectory()).path;
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
File imgFile =new File('$directory/screenshot.png');
imgFile.writeAsBytes(pngBytes);

Solution

  • 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).