c#中特定按键的监控

本文关键字:监控 | 更新日期: 2023-09-27 18:02:14

我需要编写一个Windows应用程序,该应用程序监视按键,而不考虑焦点。当它检测到一个特定的按键(特别是Ctrl + V)时,它需要执行某些操作。

无论焦点如何,我如何监控Windows中的c#按键?

c#中特定按键的监控

我不完全理解你的问题,但是如果你想注册全局键,不管你的窗口焦点,你可以使用RegisterHotKey windows API。

一个非常简单的方法是使用GetASyncKeyState。我只在游戏中使用它,但我认为它在这里也适用。

进口:

[DllImport("user32.dll")]
static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey); 

然后你可以(在循环或计时器中)

if(GetAsyncKeyState(Keys.ControlKey) && GetAsyncKeyState(Keys.K))
{
 //DO SOME STUFF!!
}

如果你想在按下时只发生一次,你可以声明

bool oldK; //at class scope

then in your loop/timer

if(!oldK && GetAsyncKeyState(Keys.ControlKey) && GetAsyncKeyState(Keys.K))
{
     //DO SOME STUFF!!
}
oldK = GetAsyncKeyState(Keys.K);

查看本文c#中按键的检测和记录

您需要将代码写入类中。然后将这个类添加到windows服务中。实例化为windows服务的start()方法。将缓冲代码放入某个计时器中如

     this.timerBuffFlush = new System.Timers.Timer();
        this.timerBuffFlush.Enabled = true;
        this.timerBuffFlush.Elapsed += new System.Timers.ElapsedEventHandler(this.timerBuffFlush_Elapsed);
        this.timerBufferFlush.Interval = 60000;
    }