c# - 我可以获得电子窗口的 MainWindowHandle 吗?
问题描述
我有一个生成 C# 应用程序的 Electron 应用程序。C# 应用程序想要获取 Electron BrowserWindow's MainWindowHandle
,但它总是返回IntPtr.Zero
,我不知道为什么。
文档说:
如果当前主窗口句柄已更改,则必须使用该
Refresh
方法刷新对象以获取当前主窗口句柄。Process
如果关联进程没有主窗口,则该
MainWindowHandle
值为零。对于已隐藏的进程,即在任务栏中不可见的进程,该值也为零。
我的 C# 应用程序运行Refresh
以防万一,我的 Electron 窗口绝对可见,我在任务栏中看到了图标:
我的 Electron 代码启动我的 C# 应用程序并将渲染器进程的 pid 发送给它(您可以下载电子快速启动应用程序并进行以下更改以重现):
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,这就是我正在使用的。
当窗口是电子/铬窗口时,我应该期望
MainWindowHandle
设置,还是这只适用于 C# 窗口?
解决方案
有一个BrowserWindow
API:
它返回您可以在任何本机 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);