是否有任何API或工具或任何方式在Windows系统上记录热键?

时间:2019-07-16 12:26:44

标签: c# .net winforms wpf-controls ui-automation

我不得不自动化一个用例,其中我必须记录所有用户动作(HotKeys,Click,Type)。有许多框架可以自动化,但是我想记录用户操作。我听说过与Windows上的应用程序通信的UI自动化,但不确定是否在屏幕上记录按键。 在此先感谢!!!

1 个答案:

答案 0 :(得分:0)

[DllImport("user32.dll", SetLastError = true)]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);

[DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

private IntPtr handle;

  public IntPtr Handle
  {
   get { return handle; }
   set { handle = value; }
  }

  public bool PreFilterMessage(ref Message m)
  {
   switch (m.Msg)
   {
    case WM_HOTKEY:
     // rise event from here
     return true;
   }
   return false;
  }

     class HotKey : IMessageFilter
     {
[DllImport("user32.dll", SetLastError = true)]
      private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError = true)]
      private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

      public enum KeyModifiers
      {
       None = 0,
       Alt = 1,
       Control = 2,
       Shift = 4,
       Windows = 8
      }

      private const int WM_HOTKEY = 0x0312;
      private const int id = 100;

      private IntPtr handle;
      public IntPtr Handle
      {
       get { return handle; }
       set { handle = value; }
      }

      private event EventHandler HotKeyPressed;

      public HotKey(Keys key, KeyModifiers modifier, EventHandler hotKeyPressed)
      {
       HotKeyPressed = hotKeyPressed;
       RegisterHotKey(key, modifier);
       Application.AddMessageFilter(this);
      }

      ~HotKey()
      {
       Application.RemoveMessageFilter(this);
       UnregisterHotKey(handle, id);
      }

      private void RegisterHotKey(Keys key, KeyModifiers modifier)
      {
       if (key == Keys.None)
        return;

       bool isKeyRegisterd = RegisterHotKey(handle, id, modifier, key);
       if (!isKeyRegisterd)
        throw new ApplicationException("Hotkey allready in use");
      }

      public bool PreFilterMessage(ref Message m)
      {
       switch (m.Msg)
       {
        case WM_HOTKEY:
         HotKeyPressed(this, new EventArgs());
         return true;
       }
       return false;
      }
     }

查看更多: Hotkeys Binding in C# Windows Application