【发布时间】:2018-07-20 15:58:34
【问题描述】:
我有一个生成 C# 应用程序的 Electron 应用程序。 C# 应用想要获取 Electron BrowserWindow 的 MainWindowHandle,但它总是返回 IntPtr.Zero,我不知道为什么。
docs 说:
您必须使用
Refresh方法刷新Process对象以获取当前主窗口句柄(如果它已更改)。如果关联进程没有主窗口,则
MainWindowHandle值为零。对于已隐藏的进程,即在任务栏中不可见的进程,该值也为零。
我的 C# 应用程序运行 Refresh 以防万一,我的 Electron 窗口绝对可见,我在任务栏中看到了图标:
我的 Electron 代码启动我的 C# 应用程序并将渲染器进程的 pid 发送给它(您可以下载 electron-quick-start 应用程序并进行以下更改以重现):
const mainWindow = new BrowserWindow({width: 800, height: 600, show: false});
mainWindow.once("ready-to-show", () => {
mainWindow.show();
});
mainWindow.once("show", () => {
// by now, our window should have launched, and we should have a pid for it
const windowPid = mainWindow.webContents.getOSProcessId();
const proc = cp.spawn("my/exeFile.exe");
// send the pid to the C# process
const buff = Buffer.allocUnsafe(4);
buff.writeIntLE(windowPid, 0, 4);
proc.stdin.write(buff);
});
C# 进程启动并加入一个无限循环的线程,该线程读取该 pid 并尝试获取其主窗口句柄:
byte[] buffer = new byte[4];
inStream.Read(buffer, 0, 4);
int pid = BitConverter.ToInt32(buffer, 0); // I've verified that the pid I'm sending is the pid I'm getting
Process proc = Process.GetProcessById(pid);
proc.Refresh(); // just in case
IntPtr windowHandler = proc.MainWindowHandle; // 0x00000000
IntPtr handle = proc.Handle; // 0x000004b8
-
我发送正确的电子 pid 了吗?我看不到我可以使用哪个其他 pid。主进程 pid 似乎不正确,所以我只剩下渲染器 pid,这就是我正在使用的。
-
当窗口是 Electron/Chromium 窗口时,我应该期望设置
MainWindowHandle,还是这只适用于 C# 窗口?
【问题讨论】: