附一下desktopCapturer的使用:
jieping() {
let that = this;
let display = screen.getPrimaryDisplay();
let scaleFactor = display.scaleFactor;
logger.log("scaleFactor:", display.bounds.width * scaleFactor);
logger.log("height:", display.bounds.height * scaleFactor);
desktopCapturer
.getSources({
types: ["screen"],
thumbnailSize: {
width: display.bounds.width * scaleFactor,
height: display.bounds.height * scaleFactor,
},
})
.then(async (sources) => {
let selectSource = sources[0];
let imageurl = selectSource.thumbnail.toDataURL("image/png");
ipcRenderer.send("jiangping_image", imageurl);
//第一次发送时窗口没创建 用localStorage传递
localStorage.setItem("jiangping_image", imageurl)
});
},
这种方案的效率还是偏低,在分辨率较高的电脑上能明显感受到延迟
官网http://www.nirsoft.net/utils/nircmd.html
链接:https://pan.baidu.com/s/1AyGNHN5XM5v08gjGx3y6Dw 提取码:sytu
nircmd.exe savescreenshot "d:\temp.png"
这种方法其实各种语言都可以使用。
把nircmd.exe
放在项目根目录的extraResources
文件夹下
const libPath = path
.join(__dirname, 'extraResources', 'nircmd.exe');
const execFileSync = require('child_process').execFileSync;
execFileSync(libPath, ['savescreenshot', 'd:\\temp001.png']);
package.json
中配置
{
"name": "mytest",
"productName": "测试项目",
"version": "1.3.8",
"description": "",
"main": "main.js",
"build": {
"asar": true,
"extraResources": [
"./extraResources/**"
]
}
}
mac的优化方案很简单,使用mac自带的命令screencapture -i
screencapture是mac自带的截图命令,有-i
和-w
两种模式,分别是自由截图和窗口截图;
screencapture -i filePath
,指定要保存的路径
screencapture -i -x filePath
,关闭截图完成后的提示音
在Electron项目中调用原生模块。研究的Electron成熟产品大多采用了这种方法,如eagle、bearychat等。这种方法还可以细分成三种:
electron作为跨平台PC开发框架,其提供了众多原生API,但毕竟需求各异,很多时候,我们仍需要实现基于C的底层业务。electron提供了nodejs调用原生模块的解决方案:使用Node原生模块
配置好node-gyp
的环境后,将c++代码暴露出供node调用的接口,修改biding.gyp。编译生成当前electron环境的addon模块,即.node文件。
node-gyp rebuild --runtime=electron --target_arch=ia32 --target=1.7.11 --disturl=https://atom.io/download/atom-shell
这是项目目前采用的方案,nodejs中通过child_process
的execFile方法去执行exe文件,exe调用同级目录下的dll,调出截图工具。
const libPath = path.join(__dirname, 'capture.exe').replace('app.asar', 'app.asar.unpacked');
clipboard.clear();
const exec = require('child_process').execFile;
exec(libPath, (err, stdout, stderr) => {
if (err) log.error('capture error', err);
log.info('capture finished', clipboard.readImage().isEmpty());
const image = clipboard.readImage();
if (!image.isEmpty()) {
// 传给UI层处理
}
})
将exe和dll文件打包到app.asar.unpacked
目录下,通过绝对路径去执行。exe和dll是网上找的的,调用并不复杂。
screenshot,一个利用微信截图dll的C#和python工具