Capture keystroke without focus in console

12,546

You can create a global keyboard hook in a console application, too.

Here's complete, working code:
https://docs.microsoft.com/en-us/archive/blogs/toub/low-level-keyboard-hook-in-c

You create a console application, but must add a reference to System.Windows.Forms for this to work. There's no reason a console app can't reference that dll.

I just created a console app using this code and verified that it gets each key pressed, whether or not the console app has the focus.

EDIT

The main thread will run Application.Run() until the application exits, e.g. via a call to Application.Exit(). The simplest way to do other work is to start a new Task to perform that work. Here's a modified version of Main() from the linked code that does this

public static void Main()
{
    var doWork = Task.Run(() =>
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
            Application.Exit(); // Quick exit for demonstration only.  
        });

    _hookID = SetHook(_proc);

    Application.Run();

    UnhookWindowsHookEx(_hookID);
}

NOTE

Possibly provide a means to exit the Console app, e.g. when a special key combo is pressed depending on your specific needs. In the

Share:
12,546
Oztaco
Author by

Oztaco

24 year old programmer, been programming for ~12 years. I like desktop programming most but I've recently been focusing on HTML5 apps. Check out my website to see some of my work

Updated on June 20, 2022

Comments

  • Oztaco
    Oztaco almost 2 years

    I know there is a question for Windows Forms but it doesn't work in the console, or at least I couldn't get it to work. I need to capture key presses even though the console doesn't have focus.