'How use the returned "buffer" of Electronjs function "getNativeWindowHandle()" in native functions?
I use the electronjs function getNativeWindowHandle() to find the HWND of electron main window.
I.e. one log was: <Buffer@0x00000293A66F0450 ec 02 07 00 00 00 00 00>
Converted to HEX: ec02070000000000
But the real HWND is: 459500, obtained doing
handleElectron.substring(0, 6).match(/.{1,2}/g), to have the three first couples of the string, then
newhandle = handleElectron[2] + handleElectron[1] + handleElectron[0]; because the handle has the the fist two and the third two chars inverted.
Then I use parseInt(handleElectron, 16) << 8) / 256 to obtain the decimal
Same result doing: user32.FindWindowW(TEXT('Chrome_WidgetWin_1'), null); (native function via node-ffi),
but I need to put it in a while loop because the FindWindowW sometimes gives 0.
Is there a cleaner and correct way to convert the result of getNativeWindowHandle() in HWND usable by FindWindowW or any other native functions?
Solution 1:[1]
The following code returns the integer value you're looking for:
const os = require("os")
function getNativeWindowHandle_Int(win) {
let hbuf = win.getNativeWindowHandle()
if (os.endianness() == "LE") {
return hbuf.readInt32LE()
}
else {
return hbuf.readInt32BE()
}
}
It appears safe to assume that Windows is Little-Endian, but the code nevertheless checks the endianness using Node's os.endianness(). About reading only 32 bits, Microsoft's documentation says the following:
When sharing a handle between 32-bit and 64-bit applications, only the lower 32 bits are significant, so it is safe to truncate the handle (when passing it from 64-bit to 32-bit) [..]
Call the function on a BrowserWindow as such:
let myWin = new BrowserWindow()
console.log(getNativeWindowHandle_Int(myWin))
Solution 2:[2]
Add an answer for Mac.
// ts
const handle = window.getNativeWindowHandle();
testNativeWindow(handle);
// mm
auto buffer = info[0].As<Napi::Buffer<uint8_t>>();
void **handle = reinterpret_cast<void **>(buffer);
NSView* electronView = (__bridge NSView *)*handle;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alex Ju |
