CapersL
CapersL

Reputation: 174

Determine Input Thread ID of a Process

Does anyone know of a way to determine the input thread of a process?

The scenario is that I would like to call GetKeyboardLayout, passing in the input thread ID from within a separate application (could be any program). Each thread can have its own keyboard input language set, but finding out the appropriate input thread ID for another process seems like something that perhaps isn't possible.

For example, I create a function into which I pass the process ID of Notepad, this function internally determines the input thread ID and returns the value from GetKeyboardLayout. The caller of this function would then display on-screen the input language selected for Notepad.

Any of you fine folks have any ideas?

Upvotes: 2

Views: 330

Answers (2)

pbhd
pbhd

Reputation: 4467

You might try that, it walks thru all toplevel-windows and searches for the one belonging to the process-id:

// complle and link with: cl layout.cxx user32.lib
#include <windows.h>
#include <stdio.h>
#include <assert.h>
DWORD desiredProcId;
BOOL CALLBACK enumCallBack(HWND hwnd, LPARAM lParam) {
  DWORD procId;
  DWORD winThread=GetWindowThreadProcessId(hwnd, &procId);
  if (procId==desiredProcId) {
    HKL hkl=GetKeyboardLayout(winThread);
    char buf[1000];
    GetWindowText (hwnd, buf, sizeof(buf));
    printf ("hwnd=%x name=%s, winThread=%x, HKL=%x\n", hwnd, buf, winThread, hkl);
    return false;
  }
  return true; 
}
int main (int argc, char *argv[]) {
  if (argc==1) {
    printf ("usage: %s processId (in decimal like from taskmanager)\n", argv[0]);
  }
  else {
    sscanf (argv[1], "%d", &desiredProcId);
    EnumWindows (enumCallBack, 0);
  }
}

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941465

Windows doesn't require a process to have a specific thread that interacts with the user. It doesn't have to be the startup thread of the process, although it often is. And it doesn't limit a program to a single thread, although it often does use only one thread.

You'll need to start by finding the window first. With api functions like FindWindow, FindWindowEx or EnumWindows. Once you got that, you can find out what thread owns the window with GetWindowThreadProcessId(). Watch out for hidden helper windows that a worker thread might create. Spy++ is your basic debugging tool here.

Upvotes: 2

Related Questions