2

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?

asked Oct 4, 2020 at 9:59

1 Answer 1

2

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;
 }
 }
 }
 }
 }
 }
}
answered Oct 4, 2020 at 12:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.