问题描述
是否可以始终不关注控制台应用程序来读取键盘输入? 我想用按钮做一些事情,而不必总是去控制台。
不是以某种方式处理事件吗?不幸的是,我只能通过Forms找到难看的解决方案。
@Siarhei Kuchuk提供的解决方案也没有帮助我: Global keyboard capture in C# application
OnKeypressed事件已激活,但未触发。
有人有什么主意吗?
解决方法
有可能。您可能会用Google搜索“键盘记录程序”,并找到许多示例,但我要给您一个非常粗糙的示例。
但首先,您必须在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;
}
}
}
}
}
}
}