C# How to stop global hotkey repeated action?

1k Views Asked by At

Problem is that when i press a global hotkey combination (ctrl + space) and hold the buttons down for a sec, the program loops it and brings up A LOT of the same text, like:

"some text" "some more text" "some text" "some more text" "some text" "some more text"

Lets say the user is old and cannot rapidly release the keyboard buttons. How to make the program perform this global hotkey action ONCE? (even if the hotkeys are pressed for a while). I tried (uint)fsModifiers.Control | (uint)fsModifiers.Norepeat but no effect. Thanks in advance!

protected override void WndProc(ref Message keyPressed)
        {
            if (keyPressed.Msg == 0x0312)
            {
                    System.Threading.Thread.Sleep(300);
                    System.Windows.Forms.SendKeys.Send("some text");
                    System.Threading.Thread.Sleep(500);
                    System.Windows.Forms.SendKeys.Send("{TAB}");
                    System.Threading.Thread.Sleep(500);
                    System.Windows.Forms.SendKeys.Send("{TAB}");
                    System.Threading.Thread.Sleep(500);
                    System.Windows.Forms.SendKeys.Send("some more text");
                    MessageBox.Show("DONE", "DONE", MessageBoxButtons.OK, MessageBoxIcon.Information);       
            }
            base.WndProc(ref keyPressed);
        }

    private void Form1_Load(object sender, EventArgs e)
    {
        RegisterHotKey(this.Handle, 1, (uint)fsModifiers.Control , (uint)Keys.Space);
    }

 public enum fsModifiers
        {
            Alt = 0x0001,
            Control = 0x0002,
            Shift = 0x0004,
            Window = 0x0008,
            Norepeat = 0x4000,
        }
1

There are 1 best solutions below

0
On

Written in C++, I don't know C# but the code show a possible solution for problem.

Solution for Alt+F2.

   static bool locked=false; 
   switch(uMsg)
   {
      case WM_HOTKEY:
      {
         if(wParam==ANY_IDENTIFIER_OF_HOTKEY && !locked)
         {
            if(windows < WINDOWS7)
            {
               locked=true;
               SetTimer(hwnd,0x665,40,NULL); 
            } 
            doAnyAction();
         }
         return 0;
      }
      case WM_TIMER:
      {
         if(wParam==0x665)
         { 
            if(!(GetAsyncKeyState(VK_F2)&0x8000)) // detected key-up
            {
               locked=false;
               KillTimer(hwnd, 0x665);
            }
         }
         return 0;
      }
      ...
   }

...

main:

   if(windows>=WINDOWS7)
      RegisterHotKey(hwnd,ANY_IDENTIFIER_OF_HOTKEY,MOD_ALT|0x4000,VK_F2);
   else
      RegisterHotKey(hwnd,ANY_IDENTIFIER_OF_HOTKEY,MOD_ALT,VK_F2);

Newer say it is impossible. It works for me.