I have an Electron app that spawns a C# app. The C# app wants to fetch the Electron BrowserWindow's MainWindowHandle
, but it always returns IntPtr.Zero
, and I don't know why.
The docs say:
You must use the
Refresh
method to refresh theProcess
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.
My C# app runs Refresh
just in case, and my Electron window is definitely visible, and I see the icon in the taskbar:
My Electron code launches my C# app and sends it the renderer process' pid (you can download the electron-quick-start app and make the following changes to reproduce):
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);
});
And the C# process starts and joins a thread with an infinite loop that reads that pid and tries to get its main window handle:
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
Am I sending the right electron pid over? I don't see which other pid I can use. The main process pid doesn't seem right, so all I'm left with is the renderer pid, which is what I'm using.
Should I expect MainWindowHandle
to be set when the window is an Electron/Chromium window, or does this only work for C# windows?
There's a BrowserWindow
API for this:
which return the HWND you can use in any native windows code
In your case I guess you can use it like this:
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);
User contributions licensed under CC BY-SA 3.0