【问题标题】:Read keyboard inputs without always having my console application focused?读取键盘输入而不总是让我的控制台应用程序专注?
【发布时间】:2020-10-04 09:59:56
【问题描述】:
【问题讨论】:
标签:
c#
console
hook
global
keyboard-hook
【解决方案1】:
这是可能的。你可以用谷歌搜索“键盘记录器”并找到很多例子,但我会给你一个非常粗略的裸露的例子。
但首先您必须添加对 System.Windows.Forms.dll 的引用才能使其正常工作
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;
}
}
}
}
}
}
}