views:

50

answers:

4

I'm creating a program that installs a keyboard hook to capture all keys and display some text related to them.

However, I've hit upon a snag, and that is some keys change behavior when the hook is installed.

I'll see about posting a small, but complete, test program, but for now I'll just describe the problem.

The problem exhibits itself on Windows 7 64-bit, in .NET 4.0, a C# program. I assume none of this matters.

My hook installs itself via SetWindowsHookEx and then handles all keys processed in the system.

If the hook method simply returns, or does minimal processing of the key (I'll post what changes the behavior in a second), the keyboard functions as expected in programs.

However, if I call this function, ToAscii from User32.dll, to figure out which key on my keyboard OemTilde or similar really is, then any key that "overlays the next key" stops functioning. I don't know the correct name for such keys, but the two apostrophe-types, ` and ´, as well as ~ and ¨, stops functioning.

For instance, if I hit ~ and then N, it displays as follows:

  • Without keyboard hook installed: ñ
  • With keyboard hook installed: n (notice no ~ above)

Does anyone know why this happens and how I can fix this problem?

For now I'll settle for just handling the keys correctly in other programs, even if that means that I won't be able to correctly detect the right key sequences in my own program.

Some more information:

If I call the ToAscii function as part of the hook method, then a different problem occurs. Keys like ¨ are processed twice, ie. if I hit the ¨ once, Notepad receives two ¨¨ characters, and hitting N now just adds the N.

However, if I use BeginInvoke to process the key on a separate thread, after returning from the keyboard hook method, the first problem occurs.


My program is probably a bit special in that:

  • I don't use keyboard state (ie. the "Key state" 256-byte array I pass around is just full of 0's)
  • I don't care about dead keys (in the sense that my program won't process them, I care just enough about them that I don't want my program to render them useless to the rest of the system)

As such, my code ended up looking as follows:

private bool IsDeadKey(uint key)
{
    return ((Hook.Interop.MapVirtualKey(key, 2) & 2147483648) == 2147483648);
}

void _Hook_KeyDown_Async(KeyDownEventArgs e)
{
    var inBuffer = new byte[2];
    char key = '\0';
    if (!IsDeadKey((uint)e.KeyCode))
    {
        int ascii = Hook.Interop.ToAscii((int) e.KeyCode,
                                            e.ScanCode,
                                            _KeyState,
                                            inBuffer,
                                            e.Flags);
        if (ascii == 1)
        {
            key = Char.ToUpper((char) inBuffer[0]);
        }
    }

    BeginInvoke(
        new Action<Keys, Boolean, Boolean, Boolean, Char>(ProcessKeyboardEvent),
        e.KeyCode, e.Control, e.Shift, e.Alt, key);
}
+1  A: 

What you're likely seeing here is the effect of trying to map a key when a dead key is involved. Keyboard mapping is a fairly involved process that has a lot of pitfalls around certain types of keys which produce this behavior.

I encourage you to read the following blog series by Michael Kaplan on the subject. It helped me sort out a number of bugs.

JaredPar
I don't actually care much about the dead keys. My program is a program that intercepts keystrokes, and can, depending on configuration files and which application is active, show what the key means, plus a visual representation of the key sequence hit to activate that function. I am wondering if just looping through all the key combinations on application startup and caching the result of ToAscii would give me what I want. What I *do* want is for keys like `OemTilde` to display the right letter, but I don't actually need the dead keys, I just need to avoid breaking their general function.
Lasse V. Karlsen
+1  A: 

These keys are called dead keys and you might be able to solve the problem by removing the call to ToAscii. See also the following related thread:

ToAscii/ToUnicode in a keyboard hook destroys dead keys.

Update: I haven't seen your code, but when processing the parameters of the KeyboardProc callback function, can you check that you pass the keyboard message on when the code parameter is less than 0? The documentation says:

code [in] int

A code the hook procedure uses to determine how to process the message. If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

There is a sample for setting up a managed hook in MSDN:

if (nCode < 0)
{
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
    // process message here

    return CallNextHookEx(hHook, nCode, wParam, lParam); 
}
0xA3
Removing the call to `ToAscii` would be nice, but since the whole point of my application is to *show* which keys you press, and many keys on international keyboards return virtual key codes that result in different keys, I need *some* way to get those keys. Perhaps I could cache all those though, that might be possible...
Lasse V. Karlsen
@Lasse V. Karlsen: I didn't dig very deep into this, but maybe you can get the character by using teh [MapVirtualKey](http://msdn.microsoft.com/en-us/library/ms646306.aspx) function?
0xA3
Or are you able to check whether a dead key was pressed *before* calling `ToAscii`/`ToUnicode`?
0xA3
I am with the use of MapVirtualKey, thanks, that was exactly what I needed. Since the keyboard state isn't used by me, and I don't care about the dead keys anyway, except that I care just enough not to want to corrupt their meaning in the rest of the system, detecting that it was a dead key before calling ToAscii was indeed the solution. I will accept your answer though all the answers here gave me useful advice.
Lasse V. Karlsen
A: 

Given the current answers and the reference to international behavior, you may need to account for "codepages." Codepages change based upon country.

Example Country Codepages

  • United States, UK 437
  • Multilingual 850
  • Slavic 852
  • Portuguese 860
  • Icelandic 861
  • Canadian, French 863
  • Scandinavian/Nordic 865

More Info

MSDN Info

Internationalization for Windows Applications

JustBoo
+1  A: 

A critical bit of information is missing from your question, which of the two keyboard hooks do you use? The easy one, WH_KEYBOARD_LL cannot work. You'll end up using the keyboard state of your program, not the program that actually gets the keystroke. Dead keys indeed make the difference.

The hard one, WH_KEYBOARD requires a hook that you cannot write in managed code. You'll need an unmanaged DLL that can be injected in every process. Once you got that, I'd just not bother with a keyboard hook, might as well log the WM_CHAR messages with WH_CALLWNDPROC.

A sample DLL is available here.

Hans Passant
I use the `_LL` version, and for my use I don't actually need the keyboard state. I managed to use the MapVirtualKey function to find if a key was a dead key, and then not call ToAscii on it, because it isn't really useful for dead keys for my use anyway.
Lasse V. Karlsen