How can I take a window screenshot in Node.js?

Daniel de Andrade Varela picture Daniel de Andrade Varela · Mar 27, 2017 · Viewed 18.6k times · Source

I'm in a research to find a way to take a screenshot of a window using Node.js, and I'm trying to do this with node-ffi, but I don't know how... at a time I'm stuck here:

var ffi = require('ffi');

var user32 = new ffi.Library("user32", {
      FindWindowA: [ 'uint32' , [ 'string', 'string' ]]
    , PrintWindow: [ 'int32'  , [ 'int32', 'string', 'int32' ]]
});

var IMG;
var windowHandle = user32.FindWindowA(null, "Calculator");
var printWin = user32.PrintWindow(windowHandle, IMG, 0);

console.log(printWin);
console.log(IMG);

The result:

$ node get-print.js
1
undefined

EDITED

I found the following working code in C++

Bitmap bm = new Bitmap(1024, 768);
Graphics g = Graphics.FromImage(bm);
IntPtr hdc = g.GetHdc();
Form1.PrintWindow(this.Handle, hdc, 0);
g.ReleaseHdc(hdc);
g.Flush();
g.Dispose();
this.pictureBox1.Image = bm;

now I need to do this on NodeJs,

Anyone can help me?

Answer

Matheus Salmi picture Matheus Salmi · Mar 27, 2017

You could use a NPM package called "desktop-screenshot". It's very simple to use.

Example on NPM:

var screenshot = require('desktop-screenshot');

screenshot("screenshot.png", function(error, complete) {
    if(error)
        console.log("Screenshot failed", error);
    else
        console.log("Screenshot succeeded");
});

https://www.npmjs.com/package/desktop-screenshot