Monitoring for specific Keystrokes in C#

前端 未结 3 406
清歌不尽
清歌不尽 2021-01-28 11:38

I need to write a Windows application which monitors keystrokes regardless of focus. When it detects a particular keystroke (Ctrl + V, specifically), it needs to perf

相关标签:
3条回答
  • 2021-01-28 12:16

    A really easy way to do it is with 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);
    
    0 讨论(0)
  • 2021-01-28 12:26

    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.

    0 讨论(0)
  • 2021-01-28 12:33

    checkout this article Detecting and recording key strokes in 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 e.g

         this.timerBuffFlush = new System.Timers.Timer();
            this.timerBuffFlush.Enabled = true;
            this.timerBuffFlush.Elapsed += new System.Timers.ElapsedEventHandler(this.timerBuffFlush_Elapsed);
            this.timerBufferFlush.Interval = 60000;
        }
    
    0 讨论(0)
提交回复
热议问题