Rumah >pembangunan bahagian belakang >C++ >Bagaimanakah saya boleh menetapkan kekunci pintas global dalam C# untuk mencetuskan peristiwa aplikasi walaupun apabila aplikasi tidak fokus?
Kod C# ini mencipta hotkey global yang mencetuskan acara walaupun apabila aplikasi diminimumkan atau tidak dalam fokus. Mari perbaiki penjelasan dan kejelasan kod untuk pemahaman yang lebih baik.
Mencipta Kekunci Panas Global dalam C#
Artikel ini menunjukkan cara melaksanakan kekunci pintas global dalam C# untuk bertindak balas kepada pintasan papan kekunci tanpa mengira fokus aplikasi. Kami akan menumpukan pada mendaftar dan mengendalikan kombinasi seperti Ctrl Alt J.
Penyelesaian: Menggunakan user32.dll
Kunci untuk mencapai ini terletak pada pustaka user32.dll
, khususnya fungsi RegisterHotKey
dan UnregisterHotKey
. Fungsi ini memerlukan pemegang tingkap; oleh itu, penyelesaian ini paling sesuai untuk aplikasi Windows Forms (WinForms). Aplikasi konsol tidak mempunyai konteks tetingkap yang diperlukan.
Pelaksanaan Kod:
Kod yang dipertingkatkan di bawah meningkatkan kebolehbacaan dan termasuk ulasan komprehensif:
<code class="language-csharp">using System; using System.Runtime.InteropServices; using System.Windows.Forms; public sealed class GlobalHotkey : IDisposable { // Import necessary functions from user32.dll [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); private const int WM_HOTKEY = 0x0312; // Windows message for hotkey events private readonly NativeWindow _window; // Internal window for message handling private int _hotKeyId; // Unique ID for each registered hotkey public GlobalHotkey() { _window = new NativeWindow(); _window.AssignHandle(new CreateParams().CreateHandle()); // Create the window handle _window.WndProc += WndProc; // Assign the window procedure } // Registers a hotkey public void Register(ModifierKeys modifiers, Keys key) { _hotKeyId++; // Generate a unique ID if (!RegisterHotKey(_window.Handle, _hotKeyId, (uint)modifiers, (uint)key)) { throw new Exception("Failed to register hotkey."); } } // Unregisters all hotkeys public void Unregister() { for (int i = 1; i <= _hotKeyId; i++) { UnregisterHotKey(_window.Handle, i); } _window.ReleaseHandle(); // Release the window handle } // Window procedure to handle hotkey messages private void WndProc(ref Message m) { if (m.Msg == WM_HOTKEY) { // Extract key and modifiers from message parameters Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); ModifierKeys modifiers = (ModifierKeys)((int)m.LParam & 0xFFFF); // Raise the HotkeyPressed event HotkeyPressed?.Invoke(this, new HotkeyPressedEventArgs(modifiers, key)); } } // Event fired when a registered hotkey is pressed public event EventHandler<HotkeyPressedEventArgs> HotkeyPressed; // IDisposable implementation public void Dispose() { Unregister(); _window.Dispose(); } } // Event arguments for HotkeyPressed event public class HotkeyPressedEventArgs : EventArgs { public ModifierKeys Modifiers { get; } public Keys Key { get; } public HotkeyPressedEventArgs(ModifierKeys modifiers, Keys key) { Modifiers = modifiers; Key = key; } } // Enum for hotkey modifiers [Flags] public enum ModifierKeys : uint { None = 0, Alt = 1, Control = 2, Shift = 4, Win = 8 }</code>
Contoh Penggunaan (WinForms):
<code class="language-csharp">public partial class Form1 : Form { private GlobalHotkey _globalHotkey; public Form1() { InitializeComponent(); _globalHotkey = new GlobalHotkey(); _globalHotkey.HotkeyPressed += GlobalHotkey_HotkeyPressed; _globalHotkey.Register(ModifierKeys.Control | ModifierKeys.Alt, Keys.J); } private void GlobalHotkey_HotkeyPressed(object sender, HotkeyPressedEventArgs e) { // Handle the hotkey press here MessageBox.Show($"Hotkey pressed: Ctrl+Alt+J"); } protected override void OnFormClosing(FormClosingEventArgs e) { _globalHotkey.Dispose(); // Important: Dispose of the hotkey when the form closes base.OnFormClosing(e); } }</code>
Ingat untuk menambah pengendalian ralat dan buang contoh GlobalHotkey
dengan betul (seperti ditunjukkan dalam OnFormClosing
) untuk mengelakkan kebocoran sumber. Kod yang disemak ini menyediakan penyelesaian yang lebih mantap dan mudah difahami untuk mengurus hotkey global dalam aplikasi C# WinForms anda.
Atas ialah kandungan terperinci Bagaimanakah saya boleh menetapkan kekunci pintas global dalam C# untuk mencetuskan peristiwa aplikasi walaupun apabila aplikasi tidak fokus?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!