1

I need to get the input from the user without pausing the application or having an event. Is there any way that I can get it without events and pausing? Since I have a timer that does other actions and I don't want to add events becuase that will result in messy code. So is there any way to get the key pressed without pausing the app or event?

Thanks.

codeforever10
  • 35
  • 1
  • 6
  • 1
    Does this answer your question? [How to set global keyboard hook on separate thread?](https://stackoverflow.com/questions/10375106/how-to-set-global-keyboard-hook-on-separate-thread) and [How to post messages to an STA thread running a message pump?](https://stackoverflow.com/questions/21680738/how-to-post-messages-to-an-sta-thread-running-a-message-pump/21684059#21684059) and [KeyHook in another thread](https://stackoverflow.com/questions/11374817/keyhook-in-another-thread) and [C# receiving keyboard hook call back in different thread](https://stackoverflow.com/questions/7227205/) –  Aug 03 '21 at 12:04
  • [GlobalKeyboardHook.cs GIST](https://gist.github.com/dudikeleti/a0ce3044b683634793cf297addbf5f11) • [KeyboardHook.cs GIST](https://gist.github.com/Lunchbox4K/291f9c8a2501170221d11d29d1355ee1) –  Aug 03 '21 at 12:05
  • 1
    `becuase that will result in messy code.` Please show us your initial messy code attempt. – mjwills Aug 03 '21 at 12:08
  • `Keyboard` class in case of WPF: https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.keyboard.iskeydown?view=net-5.0 – Dmitry Bychenko Aug 03 '21 at 12:55

1 Answers1

0

You could use the User32 API function GetKeyState which allows you to query if a key is pressed. By doing so, you wouldn't need to handle events (or hooks) separately but could do it directly in your timer method.

    [DllImport("user32")]
    public static extern short GetKeyState(int nVirtKey);

This documentation goes into more detail: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeystate

Edit: Here is an example of a method using that:

    public static bool LeftCtrlDown()
    {
        return (User32API.GetKeyState(User32API.VK_LCONTROL) & 0x8000) == 0x8000;
    }
Romout
  • 188
  • 2
  • 8