SoFunction
Updated on 2025-03-06

Methods for implementing custom hotkeys in C# programming

This article describes the method of implementing custom hotkeys in C# programming. Share it for your reference. The specific implementation method is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using .Drawing2D;
namespace App
{
 public partial class Form2 : Form
 {
  public Form2()
  {
   InitializeComponent();
   //Program loading hotkey    += delegate
   {
    // Hotkey 1: Control + left arrow of cursor    (Handle, 100, 8, );
    // Hotkey 1: Control + cursor right arrow    (Handle, 200, 2, );
    // Hotkey 1: Control + cursor arrow    (Handle, 300, 2, );
    // Hotkey 1: Control + cursor down arrow    (Handle, 400, 2, );
   };
   //Cancel the registration of hotkeys when the program exits    += delegate
   {
    (Handle, 100);
    (Handle, 200);
    (Handle, 300);
    (Handle, 400);
   };
  }
  protected override void WndProc(ref Message m)
  {
   //If the value is 0x0312, it means that the user has pressed the hotkey   const int WM_HOTKEY = 0x0312;
   switch ()
   {
    case WM_HOTKEY:
     ProcessKey(m);
     break;
   }
   (ref m);
  }
  /// <summary>
  /// Press the hotkey  /// </summary>
  /// <param name="m"></param>
  protected void ProcessKey(Message m)
  {
   //IntPtr is used to represent platform-specific types of pointers or handles   string id = ();
   (id);
   switch (id)
   {
    case "100":
     //
     break;
    case "200":
     break;
    case "300":
     break;
    case "400":
     break;
   }
  }
 }
 public class CustomSystemKeyBoard
 {
  /// <summary>
  /// Declare API functions  /// </summary>
  /// <param name="hWnd">Handle</param>
  /// <param name="id">Hotkey id</param>  /// <param name="fsModifiers">Hotkey type(KeyModifiers)</param>  /// <param name="vk">Keyboard keys</param>  /// &lt;returns&gt;&lt;/returns&gt;
  [("")]
  public static extern bool RegisterHotKey(
   IntPtr hWnd,
   int id,
   uint fsModifiers,
   Keys vk
   );
  /// &lt;summary&gt;
  /// Declare API functions  /// &lt;/summary&gt;
  /// &lt;param name="hWnd"&gt;&lt;/param&gt;
  /// &lt;param name="id"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  [("")]
  public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  /// &lt;summary&gt;
  /// Define an enumeration of KeyModifiers so that key combinations appear  /// &lt;/summary&gt;
  public enum KeyModifiers
  {
   None = 0,
   Alt = 1,
   Control = 2,
   Shift = 3,
   Windows = 8
  }
 }
}

I hope this article will be helpful to everyone's C# programming.