Capture keystroke without focus in console

2019-01-14 19:22发布

I know there is a question for windows forms but it doesnt work in the console, or at least i couldnt get it to work. I need to capture key presses even though the console doesnt have focus

1条回答
冷血范
2楼-- · 2019-01-14 20:01

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

Here's complete, working code:

http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

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 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

查看更多
登录 后发表回答