c# - 我可以获得 Electron 窗口的 MainWindowHandle 吗?

标签 c# window electron

我有一个 Electron 应用程序,它生成一个 C# 应用程序。 C# 应用程序想要获取 Electron BrowserWindow 的 MainWindowHandle,但它总是返回 IntPtr.Zero,我不知道为什么。

docs说:

You must use the Refresh method to refresh the Process object to get the current main window handle if it has changed.

If the associated process does not have a main window, the MainWindowHandle value is zero. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar.

我的 C# 应用程序运行 Refresh 以防万一,我的 Electron 窗口绝对可见,并且我在任务栏中看到了该图标:

enter image description here

我的 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
  1. 我发送的 Electron pid 是否正确?我不知道我可以使用哪个其他 pid。主进程 pid 似乎不正确,所以我只剩下渲染器 pid,这就是我正在使用的。

  2. 当窗口是 Electron/Chromium 窗口时,我是否应该设置 MainWindowHandle,或者这仅适用于 C# 窗口?

最佳答案

有一个 BrowserWindow API 可以实现此目的:

win.getNativeWindowHandle()

返回可在任何 native Windows 代码中使用的 HWND

就你的情况而言,我想你可以这样使用它:

byte[] bytes = new byte[8];
for (int i = 0; i < data.Length; i++) {
  object item = data[i];
  bytes[i] = (byte)(int)item;
}
return BitConverter.ToUInt64(bytes, 0);

关于c# - 我可以获得 Electron 窗口的 MainWindowHandle 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446359/

相关文章:

javascript - 如何读取 HTML 文档文本并替换 API 调用响应中括号内的字符串

c# - 您将全局变量放在 WPF 应用程序的什么位置?

wpf - WPF 窗口关闭后会发生什么?

java - 清除 NetBeans 中的输出窗口

node.js - 能够为每个BrowserWindow对象创建一个新 session ?

javascript - Electron 中的假 Document.visibilityState

c# - LINQ 查询中的三元运算符

java - 将多个二进制文件复制到一个二进制文件

javascript - 传单在 Electron 中翻转瓷砖

c# - 仅用于内容文件的 Nuget 包