Eli Zaretskii writes: >> Is there a better place where the remove_w32_kbdhook call could go such >> that cleanup can always happen? > > I think that place is term_ntproc. I have added a call to ‘remove_w32_kbdhook’ there, but also left it with the WM_DESTROY message. The cleanup now always happens and the setup/remove calls are correctly nested when using multiple frames. >> >> Unfortunately, this didn't work for me. I tried calling >> >> ‘EnumWindows(find_child_console, ...)’ with a ‘child_process’ instance >> >> containing the current process id as returned by ‘GetCurrentProcessId’, >> >> but I don't seem to get a useful window handle. >> > >> > What do you mean? What is the result of using find_child_console? >> > does the condition in find_child_console, which looks at the >> > process_id of all windows, never match the process ID of the Emacs >> > session running with -nw? Or what else goes wrong? I figured this out now. The ‘find_child_console’ function looks for a ‘ConsoleWindowClass’ window, but the Emacs process itself only has ‘Emacs Clipboard’ and ‘IME’ windows. The latter seems to be the one I need. I added a function ‘find_ime_window’ in ‘w32console.c’ that checks for this window when called through ‘EnumThreadWindows’. I can now register for session notifications using this window. To handle the notifications, I added some code to ‘drain_message_queue’, calling ‘reset_w32_kbdhook_state’ from there. This now correctly resets the hook state in console Emacs. I added ‘WINDOWSNT’ #ifdefs around calls to and the definition of ‘reset_w32_kbdhook_state’, as with the setup/remove functions. I also cleaned up the ‘remove_w32_kbdhook’ function to use the previously obtained function pointer. I believe the attached version should now tick all the important boxes. Regards, Raffael