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

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

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

Всем доброго вечера. Хотелось реализовать программу которая будет при нажатии скажем Pause/Break? открывает Form2, пробовал так
Листинг программы
  1. KeyPreview = true;
  2. KeyDown += new KeyEventHandler(Form_KeyDown);
  3. void Form_KeyDown(object o, KeyEventArgs e)
  4. {
  5. // Ctrl + X
  6. if (e.KeyCode == Keys.Z)
  7. {
  8. // Выполнить нужное действие, например, открыть форму
  9. Form4 f = new Form4(); // создаем
  10. f.Show(); // или так
  11. }
  12. }
Но Form2 открывается только когда программа развёрнута и я нахожусь в ней, а надо что бы Form2 открывался в любом случае когда программа запущена даже если она в трее, если я играю в игру, или ещё что то делаю. Например Pinto Swither всегда реагирует на нажатие клавиш на клавиатуре.

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

textual
Листинг программы
  1. using System;
  2. using System.ComponentModel;
  3. using System.Runtime.InteropServices;
  4. using System.Windows.Forms;
  5.  
  6. namespace <br>
  7. {
  8.     /// <summary>
  9.     /// Specifies key modifiers.
  10.     /// </summary>
  11.     [Flags]
  12.     public enum KeyModifiers : uint
  13.     {
  14.         /// <summary>
  15.         /// Empty modifiers
  16.         /// </summary>
  17.         None                = 0x0000,
  18.         /// <summary>
  19.         /// Either ALT key must be held down.
  20.         /// </summary>
  21.         Alt                 = 0x0001,
  22.         /// <summary>
  23.         /// Either CTRL key must be held down.
  24.         /// </summary>
  25.         Control             = 0x0002,
  26.         /// <summary>
  27.         /// Either SHIFT key must be held down.
  28.         /// </summary>
  29.         Shift               = 0x0004,
  30.         /// <summary>
  31.         /// Either WINDOWS key was held down.
  32.         /// These keys are labeled with the Windows logo.
  33.         /// Keyboard shortcuts that involve the WINDOWS key are reserved for use by the operating system.
  34.         /// </summary>
  35.         Windows             = 0x0008,
  36.         //IgnoreAllModifier   = 0x0400,
  37.         //OnKeyUp             = 0x0800,
  38.         //MouseRight          = 0x4000,
  39.         //MouseLeft           = 0x8000,
  40.     }
  41.  
  42.     public class HotKey : IMessageFilter, IDisposable
  43.     {
  44.         #region Extern
  45.         const int WM_HOTKEY = 0x312;
  46.         const int ERROR_HOTKEY_ALREADY_REGISTERED = 0x581;
  47.  
  48.         [DllImport("user32.dll", SetLastError = true)]
  49.         [return: MarshalAs(UnmanagedType.Bool)]
  50.         static extern bool RegisterHotKey(IntPtr hWnd, IntPtr id, KeyModifiers fsModifiers, Keys vk);
  51.  
  52.         [DllImport("user32.dll", SetLastError = true)]
  53.         [return: MarshalAs(UnmanagedType.Bool)]
  54.         static extern bool UnregisterHotKey(IntPtr hWnd, IntPtr id);
  55.         #endregion
  56.  
  57.         private IntPtr windowHandle;
  58.         public event HandledEventHandler Pressed;
  59.  
  60.         public HotKey()
  61.             : this(Keys.None, KeyModifiers.None)
  62.         {
  63.         }
  64.  
  65.         public HotKey(Keys keyCode, KeyModifiers modifiers)
  66.         {
  67.             this.KeyCode    = keyCode;
  68.             this.Modifiers  = modifiers;
  69.             Application.AddMessageFilter(this);
  70.         }
  71.  
  72.         ~HotKey()
  73.         {
  74.             this.Dispose();
  75.         }
  76.  
  77.         public void Dispose()
  78.         {
  79.             if (this.IsRegistered)
  80.                 this.Unregister();
  81.  
  82.             this.windowHandle   = IntPtr.Zero;
  83.             this.Modifiers      = KeyModifiers.None;
  84.             this.KeyCode        = Keys.None;
  85.             this.Tag            = 0;
  86.         }
  87.  
  88.         private bool OnPressed()
  89.         {
  90.             HandledEventArgs e = new HandledEventArgs(false);
  91.             if (this.Pressed != null)
  92.                 this.Pressed(this, e);
  93.  
  94.             return e.Handled;
  95.         }
  96.  
  97.         /// <summary>
  98.         /// Filters out a message before it is dispatched.
  99.         /// </summary>
  100.         /// <param name="message">
  101.         /// The message to be dispatched. You cannot modify this message.
  102.         /// </param>
  103.         /// <returns>
  104.         /// true to filter the message and stop it from being dispatched;
  105.         /// false to allow the message to continue to the next filter or control.
  106.         /// </returns>
  107.         public bool PreFilterMessage(ref Message message)
  108.         {
  109.             if (message.Msg != WM_HOTKEY || !this.IsRegistered)
  110.                 return false;
  111.  
  112.             if (message.WParam == this.Guid)
  113.                 return this.OnPressed();
  114.  
  115.             return false;
  116.         }
  117.  
  118.         /// <summary>
  119.         /// Defines a system-wide hot key.
  120.         /// </summary>
  121.         /// <param name="windowControl">
  122.         /// A handle to the window that will receive messages generated by the hot key.
  123.         /// </param>
  124.         public void Register(Control window)
  125.         {
  126.             if (this.IsRegistered)
  127.                 throw new NotSupportedException("You cannot register a hotkey that is already registered");
  128.  
  129.             if (this.IsEmpty)
  130.                 throw new NotSupportedException("You cannot register an empty hotkey");
  131.  
  132.             if (window.IsDisposed)
  133.                 throw new ArgumentNullException("window");
  134.  
  135.             this.windowHandle = window.Handle;
  136.  
  137.             if (!RegisterHotKey(this.windowHandle, this.Guid, this.Modifiers, this.KeyCode))
  138.             {
  139.                 if (Marshal.GetLastWin32Error() != ERROR_HOTKEY_ALREADY_REGISTERED)
  140.                     throw new Win32Exception();
  141.             }
  142.             this.IsRegistered = true;
  143.         }
  144.  
  145.         /// <summary>
  146.         /// Frees a hot key previously registered by the calling thread.
  147.         /// </summary>
  148.         public void Unregister()
  149.         {
  150.             if (!this.IsRegistered)
  151.                 return;
  152.  
  153.             if (!UnregisterHotKey(this.windowHandle, this.Guid))
  154.                 throw new Win32Exception();
  155.  
  156.             this.IsRegistered = false;
  157.         }
  158.  
  159.         public bool HasModifier(KeyModifiers modifiers)
  160.         {
  161.             return (this.Modifiers & modifiers) != 0;
  162.         }
  163.  
  164.         public static HotKey Parse(object content)
  165.         {
  166.             if (content == null)
  167.                 return new HotKey();
  168.  
  169.             return Parse(content.ToString());
  170.         }
  171.  
  172.         #region Fields
  173.  
  174.         private IntPtr Guid
  175.         {
  176.             get { return new IntPtr((int)Modifiers << 16 | (int)KeyCode & 0xFFFF); }
  177.         }
  178.  
  179.         public bool IsEmpty
  180.         {
  181.             get { return (this.KeyCode == Keys.None); }
  182.         }
  183.  
  184.         public bool IsRegistered { get; private set; }
  185.  
  186.         public KeyModifiers Modifiers { get; private set; }
  187.  
  188.         public Keys KeyCode { get; private set; }
  189.  
  190.         public int Tag { get; set; }
  191.  
  192.         #endregion
  193.     }
  194. }

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


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

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

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

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

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

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