none
全局热键问题 RRS feed

  • 问题

  • 在未如的窗口上(当前的运行的窗口不知道是哪个),当按键盘“A”时弹出一个消息框。怎么实现?

    2012年3月27日 7:41

答案

  • 先要说明的是,能够实现的也只能是系统未定义过的快捷键,如果你按下的系统定义过的快捷键的话,系统会相应快捷键操作,而忽略你的操作。

    然后下面是实现代码:

      public partial class MainWindow : Window
      {
        public MainWindow()
        {
          InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
          new KeyboardHandler(this);
        }
      }
    
      public class KeyboardHandler : IDisposable
      {
    
        public const int WM_HOTKEY = 0x0312;
        public const int VIRTUALKEYCODE_A = 0x41;  // A virtual-key, refer to: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
    
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    
        private readonly Window _mainWindow;
        WindowInteropHelper _host;
    
        public KeyboardHandler(Window mainWindow)
        {
          _mainWindow = mainWindow;
          _host = new WindowInteropHelper(_mainWindow);
    
          SetupHotKey(_host.Handle);
          ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
        }
    
        void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
          if (msg.message == WM_HOTKEY)
          {
            MessageBox.Show("A hot key ws preesed");
          }
        }
    
        private void SetupHotKey(IntPtr handle)
        {
          RegisterHotKey(handle, GetType().GetHashCode(), 0, VIRTUALKEYCODE_A);
        }
    
        public void Dispose()
        {
          UnregisterHotKey(_host.Handle, GetType().GetHashCode());
        }
      }

    XAML:

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Loaded="Window_Loaded"
            Title="MainWindow" Height="350" Width="525">
      ...


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us

    • 已标记为答案 WCF小Q 2012年3月28日 0:32
    2012年3月27日 16:38
    版主