Can I get the MainWindowHandle of an Electron window?

1

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 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.

My C# app runs Refresh just in case, and my Electron window is definitely visible, and I see the icon in the taskbar:

enter image description here

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
  1. 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.

  2. Should I expect MainWindowHandle to be set when the window is an Electron/Chromium window, or does this only work for C# windows?

c#
window
electron
asked on Stack Overflow Jul 20, 2018 by pushkin • edited Jun 20, 2020 by Community

1 Answer

3

There's a BrowserWindow API for this:

win.getNativeWindowHandle()

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);
answered on Stack Overflow Jul 25, 2018 by pergy • edited Jul 27, 2018 by pergy

User contributions licensed under CC BY-SA 3.0