简体   繁体   English

退出前捕获 Electron 窗口的屏幕截图

[英]Capture screenshot of Electron window before quitting

In an Electron app, I can take a screenshot of my window from the main process using this:在 Electron 应用程序中,我可以使用以下命令从主进程中截取我的窗口的屏幕截图:

let win = new BrowserWindow(/* ... */);
let capturedPicFilePath = /* where I want that saved */
win.capturePage((img) => {
    fs.writeFile(capturedPicFilePath, img.toPng(), () => console.log(`Saved ${capturedPicFilePath}`))
})

Awesome.惊人的。 Now I'd like to do that right before app quits.现在我想在应用程序退出之前这样做。 Electron emits a particular event for that, that I tried to use: Electron 为此发出一个特定事件,我尝试使用该事件

Event: 'before-quit' : emitted before the application starts closing its windows.事件: 'before-quit' :在应用程序开始关闭其窗口之前发出。

Problem : if I use the same code as above in a handler for that event, the file is created but empty.问题:如果我在该事件的处理程序中使用与上述相同的代码,则该文件已创建但为空。

I'm guessing it's because the screenshot is taken in an asynchronous way, and the window is already closed when it happens.我猜是因为截图是异步的,发生的时候窗口已经关闭了。

So this does not work for me:所以这对我不起作用:

app.on('before-quit', (event) => {
    win.capturePage(function(img) {
        fs.writeFile(capturedPicFilePath, img.toPng(), () => console.log(`Saved ${capturedPicFilePath}`))
    })
})

Edit 1 : Doing this in the renderer process with window.onbeforeunload fails too.编辑 1:在使用window.onbeforeunload的渲染器进程中执行此操作也失败。 It's also too late to perform the screenshot.执行屏幕截图也为时已晚。 I get this in the main console (ie it goes to terminal):我在主控制台中得到这个(即它进入终端):

Attempting to call a function in a renderer window that has been closed or released.试图在已关闭或释放的渲染器窗口中调用函数。

Context: for now I'm exploring the limits of what is possible to do with screen capture (essentially for support purposes), and found that one.上下文:现在我正在探索屏幕捕获可能做的限制(主要是为了支持目的),并找到了一个。 Not sure yet what I would do with that edge case, I thought about it not just for support, I'm also considering displaying at startup a blurred pic of previous state (some parts of my app take 1-2 seconds to load).还不确定我会用那个边缘情况做什么,我考虑它不仅仅是为了支持,我还考虑在启动时显示先前状态的模糊图片(我的应用程序的某些部分需要 1-2 秒才能加载)。

Any ideas?有任何想法吗?

I have had a similar problem before, I got around it by using the window close event and then preventing it from closing.我以前遇到过类似的问题,我通过使用窗口关闭事件然后阻止它关闭来解决它。 Once my action had performed I then ran app.quit() .一旦我的动作执行app.quit()我就运行app.quit()

window.on('close', function (event) {
    event.preventDefault();

    let capturedPicFilePath = /* where you want it saved */
    window.capturePage((img) => {
        fs.writeFile(capturedPicFilePath, img.toPng(), () => 
        console.log(`Saved ${capturedPicFilePath}`));

        app.quit(); // quit once screenshot has saved.
    });
});

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM