简体   繁体   中英

Get thread ID of current active window

I need to obtain the thread ID of the active window. Is there a Windows API function that will let me obtain this information?

There is the GetCurrentThreadId function, but it returns an ID for the calling thread, not the active window thread, so it's not useful for this purpose.

EDIT:

As suggested to edit my question to provide additional information on why do I need this, here it is:

I'm implementing a LowLevelKeyboardProc to capture keyboard input, and since keyboard layout can vary from program to program I want to ensure the layout is obtained for active window that processes the keyboard:

code snippet:

HWND active_window = GetForegroundWindow();
DWORD thread_id = GetWindowThreadProcessId(active_window, nullptr);
HKL hLayout = GetKeyboardLayout(thread_id);

Now having the correct keyboard layout for active window I translate the key:

BYTE pKeyState[256];
GetKeyboardState(pKeyState)

wchar_t result;
PKBDLLHOOKSTRUCT pKbd = reinterpret_cast<PKBDLLHOOKSTRUCT>(lParam);
ToUnicodeEx(pKbd->vkCode, pKbd->scanCode, pKeyState, &result, 1, 2, hLayout);

The answer provided suits my needs, because if passing zero to GetKeyboardLayout function the keyboard layout will be wrong (the same) if user changes keyboard layout during program execution. Passing active window thread id is the way to go.

You can get the ID of the thread which created the active window, though of course there might be other threads somehow involved with it since its creation.

If that's what you're after, use GetWindowThreadProcessId ( GetForegroundWindow() , nullptr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM