Electron 通过WM进程操作

基础操作

  1. 启动进程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const { exec } = require("child_process");
    exec('start ' + exePath, (error, stdout, stderr) => {
    if (error) {
    console.log('ComeCapture启动失败');
    return;
    }
    findHwnd();
    });

  2. 获取句柄

    1
    user32.FindWindowW(null, Text('ComeCapture'));
  3. 显示进程窗口

    1
    user32.ShowWindow(hwnd, 3);
  4. 发送指令

    1
    user32.SendMessageW(hwnd, 16, 0, 0);

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const ffi = require('ffi-napi')
const { exec } = require("child_process");
var screenshot = function() {

var user32 = new ffi.Library("user32", {
'ShowWindow': ['int', ['int', 'int']],
'FindWindowW': ['int', ['string', 'string']],
'DestroyWindow': ['bool', ['int']],
'SendMessageW': ['int', ['int', 'int', 'long', 'long']]
})
var hwnd = null;
var errorCount = 0;
const exePath = "D:\\Test\\screenshot\\ComeCapture\\bin\\Debug\\ComeCapture.exe";

function Text(text) {
return Buffer.from(`${text}\0`, "ucs2");
}

function start() {
exec('start ' + exePath, (error, stdout, stderr) => {
if (error) {
console.log('ComeCapture启动失败');
return;
}
findHwnd();
});
}

function findHwnd() {
//获取截图窗体句柄
return new Promise((resolve, reject) => {
let result = user32.FindWindowW(null, Text('ComeCapture'));
if (result == 0) {
if (errorCount > 5) {
errorCount = 0;
start();
return;
}
errorCount++;
setTimeout(() => {
findHwnd();
}, 200)
} else {
//hwnd = result.toString(16);
hwnd = result;
errorCount = 0;
console.log("ComeCapture hwnd:" + hwnd);
resolve();
}
})

}


function run() {
findHwnd().then(() => {
user32.ShowWindow(hwnd, 3);
});
}

function dispose() {
findHwnd().then(() => {
user32.SendMessageW(hwnd, 16, 0, 0);
});

}
return {
init: () => start(),
run: () => run(),
dispose: () => dispose()
}
}
module.exports = new screenshot();