views:

1218

answers:

4

I'm writing a program in C# that runs in the background and allows users to use a htokey to switch keyboard layouts in the active window. (Windows only supports CTRL+SHIFT & ALT+SHIFT)

I'm using RegisterHotKey to catch the hotkey, & it's working fine.

The problem is that I can't find any API to change the keyboard layout for the focused window.

ActivateKeyboardLayout and LoadKeyboardLayout can only change the keyboard layout for the calling thread.

Does anyone know how to change the keyboard layout for a different thread (the way the Language Bar does)?

+1  A: 

I think the trick is to get your code to execute in the context of the thread whose keyboard layout you wish to change. You'll need to do some win32 interop here and learn about DLL Injection to get your code to execute in the remote thread.

A keyboard hook handler looks like a good option for you here.

Take a look at http://www.codeproject.com/KB/threads/winspy.aspx

Sijin
A: 

Another way that may be acceptable if you are writing something just for yourself: define a separate key combination for every layout (such as Alt+Shift+1, etc), and use SendInput to switch between them.

The circumstances in which this is usable are limited of course.

romkyns
+1  A: 
PostMessage(handle,WM_INPUTLANGCHANGEREQUEST,0,LoadKeyboardLayout( StrCopy(Layout,'00000419'),KLF_ACTIVATE);
Ramil
but this works correctly. :-)
Ramil
A: 
  function ChangeRemoteWndKeyboardLayoutToRussian(
    const RemoteHandle: THandle): Boolean;
  var
    Dumme: DWORD;
    Layout: HKL;
  begin
    Layout := LoadKeyboardLayout('00000419', KLF_ACTIVATE);
    Result := SendMessageTimeOut(RemoteHandle, WM_INPUTLANGCHANGEREQUEST,
      0, Layout, SMTO_ABORTIFHUNG, 200, Dumme) <> 0;
    if Result then    
      Result := SendMessageTimeOut(RemoteHandle, WM_INPUTLANGCHANGEREQUEST,
        RUSSIAN_CHARSET, Layout, SMTO_ABORTIFHUNG, 200, Dumme) <> 0;
  end;
Ramil
This doesn't work across processes, if I remember correctly.
SLaks