waitingsong / node-win32-api

win32 api
MIT License
430 stars 55 forks source link

Bug in "Async Find window and set window title" #36

Closed somanuell closed 2 years ago

somanuell commented 2 years ago

The sample titled "Async Find window and set window title" in README.md contains the code:

const buf = Buffer.alloc(title.length * 2)
u32.GetWindowTextW.async(hWnd, buf, buf.byteLength, err3 => {

But the Win32 API GetWindowTextW wants a character count as third parameter, not a byte count. In unicode a character is two bytes.

So the code should be (imho):

const buf = Buffer.alloc(title.length * 2)
u32.GetWindowTextW.async(hWnd, buf, title.length, err3 => {
somanuell commented 2 years ago

By passing buf.byteLength, you tell the API that you have allocated a buffer twice as big as you really did. If title.length is actually the real length of the text, the API will write an extra binary zero beyond the allocated space. Some 32 bits versions of node.exe do not care, that's for sure. But if you greatly underestimate title.length, then node.exe will just crash! No crash is possible if you always pass the allocated size / 2...

waitingsong commented 2 years ago

got it

waitingsong commented 2 years ago

fixed