Search code examples
c#consolehookglobalkeyboard-hook

Read keyboard inputs without always having my console application focused?


is it possible to read keyboard inputs without always having my console application focused? I would like to do something with a button without always going to the console.

Doesn't that somehow work with events? Unfortunately I only found unsightly solutions with Forms.

This solution from @Siarhei Kuchuk didn't help me either: Global keyboard capture in C# application

The OnKeyPressed event is activated but is not triggered.

Does somebody has any idea?


Solution

  • That's possible. You may google "keyloggers" and find many examples but I'm gonna give you a very rough bare boned one. But first you have to add a refrence to System.Windows.Forms.dll for this to work

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Threading;
    
    namespace ConsoleApp1
    {
        class Program
        {
            [DllImport("User32.dll")]
            private static extern short GetAsyncKeyState(System.Int32 vKey);
            static void Main(string[] args)
            {
                while (true)
                {
                    Thread.Sleep(500);
                    for (int i = 0; i < 255; i++)
                    {
                        int state = GetAsyncKeyState(i);
                        if (state != 0)
                        {
                            string pressedKey= ((System.Windows.Forms.Keys)i).ToString();
                            switch (pressedKey)
                            {
    
                                default:
                                    Console.WriteLine("You have pressed: " + pressedKey);
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }