Глобальный прехват нажатия клавиш - C#

Узнай цену своей работы

Формулировка задачи:

Нужно, что бы программка перехватила нажатие какой-то клавиши, с условием, что пользователь может работать и в другом окне. В конкретном случае нажатие клавиши будет прерывать работу программы.. Вот только как организовать перехват? С примером кода, пожалуйста

Решение задачи: «Глобальный прехват нажатия клавиш»

textual
Листинг программы
  1. public sealed class KeyboardHook : IDisposable
  2. {
  3.     // Registers a hot key with Windows.
  4.     [DllImport(“user32.dll”)]
  5.     private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
  6.     // Unregisters the hot key with Windows.
  7.     [DllImport(“user32.dll”)]
  8.     private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  9.  
  10.  
  11.     /// <summary>
  12.     /// Represents the window that is used internally to get the messages.
  13.     /// </summary>
  14.     private class Window : NativeWindow, IDisposable
  15.     {
  16.         private static int WM_HOTKEY = 0Г—0312;
  17.  
  18.         public Window()
  19.         {
  20.             // create the handle for the window.
  21.             this.CreateHandle(new CreateParams());
  22.         }
  23.  
  24.         /// <summary>
  25.         /// Overridden to get the notifications.
  26.         /// </summary>
  27.         /// <param name="m"></param>
  28.         protected override void WndProc(ref Message m)
  29.         {
  30.             base.WndProc(ref m);
  31.  
  32.             // check if we got a hot key pressed.
  33.             if (m.Msg == WM_HOTKEY)
  34.             {
  35.                 // get the keys.
  36.                 Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
  37.                 ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);
  38.  
  39.                 // invoke the event to notify the parent.
  40.                 if (KeyPressed != null)
  41.                     KeyPressed(this, new KeyPressedEventArgs(modifier, key));
  42.             }
  43.         }
  44.  
  45.         public event EventHandler<KeyPressedEventArgs> KeyPressed;
  46.  
  47.         #region IDisposable Members
  48.  
  49.         public void Dispose()
  50.         {
  51.             this.DestroyHandle();
  52.         }
  53.  
  54.         #endregion
  55.     }
  56.  
  57.     private Window _window = new Window();
  58.     private int _currentId;
  59.  
  60.     public KeyboardHook()
  61.     {
  62.         // register the event of the inner native window.
  63.         _window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
  64.         {
  65.             if (KeyPressed != null)
  66.                 KeyPressed(this, args);
  67.         };
  68.     }
  69.  
  70.     /// <summary>
  71.     /// Registers a hot key in the system.
  72.     /// </summary>
  73.     /// <param name="modifier">The modifiers that are associated with the hot key.</param>
  74.     /// <param name="key">The key itself that is associated with the hot key.</param>
  75.     public void RegisterHotKey(ModifierKeys modifier, Keys key)
  76.     {
  77.         // increment the counter.
  78.         _currentId = _currentId + 1;
  79.  
  80.         // register the hot key.
  81.         if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
  82.             throw new InvalidOperationException(“Couldnt register the hot key.”);
  83.     }
  84.  
  85.     /// <summary>
  86.     /// A hot key has been pressed.
  87.     /// </summary>
  88.     public event EventHandler<KeyPressedEventArgs> KeyPressed;
  89.  
  90.     #region IDisposable Members
  91.  
  92.     public void Dispose()
  93.     {
  94.         // unregister all the registered hot keys.
  95.         for (int i = _currentId; i > 0; i–)
  96.         {
  97.             UnregisterHotKey(_window.Handle, i);
  98.         }
  99.  
  100.         // dispose the inner native window.
  101.         _window.Dispose();
  102.     }
  103.  
  104.     #endregion
  105. }
  106.  
  107. /// <summary>
  108. /// Event Args for the event that is fired after the hot key has been pressed.
  109. /// </summary>
  110. public class KeyPressedEventArgs : EventArgs
  111. {
  112.     private ModifierKeys _modifier;
  113.     private Keys _key;
  114.  
  115.     internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
  116.     {
  117.         _modifier = modifier;
  118.         _key = key;
  119.     }
  120.  
  121.     public ModifierKeys Modifier
  122.     {
  123.         get { return _modifier; }
  124.     }
  125.  
  126.     public Keys Key
  127.     {
  128.         get { return _key; }
  129.     }
  130. }
  131.  
  132. /// <summary>
  133. /// The enumeration of possible modifiers.
  134. /// </summary>
  135. [Flags]
  136. public enum ModifierKeys : uint
  137. {
  138.     Alt = 1,
  139.     Control = 2,
  140.     Shift = 4,
  141.     Win = 8
  142. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 3.917 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут