Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture keystroke without focus in console

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.

like image 445
Oztaco Avatar asked Jun 11 '12 22:06

Oztaco


1 Answers

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

Here's complete, working code:
https://learn.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

like image 122
Eric J. Avatar answered Nov 16 '22 16:11

Eric J.