gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:50 25 4
gpt4 key购买 nike

我有一个生成 C# 应用程序的 Electron 应用程序。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com