1

I'm trying to get the key the user pressed from another app but all i can get is the location of the key that has been pressed without the keyboard condition (uppercase/lowercase/shift pressed) and i want to get the actual key

my code:

   private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;
    private static int enteredChar;
    public static int EnteredChar
    {
        get { return enteredChar; }
    }
    public static void start()
    {
        _hookID = SetHook(_proc);
        Application.Run();

        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {

        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            //  char letter=(char) Marshal.ReadByte(lParam);
           enteredChar = Marshal.ReadInt32(lParam);
              Console.WriteLine((Keys)enteredChar);

        }

        return CallNextHookEx(_hookID, nCode, wParam, lParam);

    }
    public static int returnKey()
    {
        return enteredChar;
    }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user1839169
  • 207
  • 2
  • 4
  • 16
  • When you intercept a key, you should get the Keyboard State separately to see which modifiers were pressed. Look here: http://stackoverflow.com/questions/1100285/how-to-detect-the-currently-pressed-key – SimpleVar Nov 25 '12 at 14:51
  • what's purpose of getting key from other app? If you wan't global hotkey you can use RegisterHotKey. Getting keys by hooks from another process can make antyvirus false-positive. However you can also get system-wide pressed keys with Managed.DirectX.DirectInput :P – fex Nov 25 '12 at 15:05
  • This is simply not possible with a low-level hook. You need a global hook so you can see the WM_CHAR messages that get generated by things like dead keys and IMEs. You can't write a global hook in C#. – Hans Passant Nov 25 '12 at 16:43
  • so how can i write a global hook? – user1839169 Nov 25 '12 at 17:02

0 Answers0