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

pus*_*kin 3 c# window electron

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

文档说

如果当前主窗口句柄已更改,则必须使用该Refresh方法刷新对象以获取当前主窗口句柄。Process

如果关联进程没有主窗口,则该MainWindowHandle值为零。对于已隐藏的进程(即在任务栏中不可见的进程),该值也为零。

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

在此输入图像描述

我的 Electron 代码启动我的 C# 应用程序并向其发送渲染器进程的 pid(您可以下载electro-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);
});
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)
  1. 我发送了正确的电子 pid 了吗?我不知道我可以使用哪个其他 pid。主进程 pid 似乎不正确,所以我只剩下渲染器 pid,这就是我正在使用的。

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

per*_*rgy 5

有一个BrowserWindowAPI 可以实现此目的:

win.getNativeWindowHandle()

它返回可以在任何本机 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);
Run Code Online (Sandbox Code Playgroud)