简体   繁体   English

监控 C# 中的特定击键

[英]Monitoring for specific Keystrokes in C#

I need to write a Windows application which monitors keystrokes regardless of focus.我需要编写一个 Windows 应用程序来监控击键而不考虑焦点。 When it detects a particular keystroke ( Ctrl + V , specifically), it needs to perform certain actions.当它检测到特定的击键(特别是Ctrl + V )时,它需要执行某些操作。

How can I monitor keystrokes in Windows from C# regardless of focus?无论焦点如何,如何从 C# 监控 Windows 中的击键?

I am not fully understand your question, but If you would like to register global key regardless of your window focus you can use RegisterHotKey windows API.我不完全理解您的问题,但是如果您想注册全局密钥而不管您的 window 焦点如何,您可以使用RegisterHotKey windows API。

A really easy way to do it is with GetASyncKeyState.一个非常简单的方法是使用 GetASyncKeyState。 I use it only for games but I think it would work here.我只将它用于游戏,但我认为它可以在这里工作。

Import this:导入这个:

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

Then you can just do (in a loop or timer)然后你可以做(在循环或计时器中)

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

If you need it to happen just once when it's pressed you can declare如果您需要它在按下时只发生一次,您可以声明

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);

checkout this article Detecting and recording key strokes in C#结帐这篇文章检测和记录 C# 中的击键

you need to write the code into a class.Then add this class to a windows service.Instaniate into start() method of windows service.olace the buffering code into some timer eg you need to write the code into a class.Then add this class to a windows service.Instaniate into start() method of windows service.olace the buffering code into some timer eg

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM