此 C# 程式碼建立一個全域熱鍵,即使應用程式最小化或未獲得焦點,該熱鍵也會觸發事件。 讓我們改進解釋和程式碼清晰度,以便更好地理解。
在 C# 中建立全域熱鍵
本文示範如何在 C# 中實現全域熱鍵,以響應鍵盤快捷鍵,而不管應用程式焦點如何。 我們將重點放在註冊和處理 Ctrl Alt J 等組合。
解:使用user32.dll
實現這一目標的關鍵在於 user32.dll
函式庫,特別是 RegisterHotKey
和 UnregisterHotKey
函數。 這些函數需要一個視窗句柄;因此,該解決方案最適合 Windows 窗體應用程式 (WinForms)。 控制台應用程式缺乏必要的視窗上下文。
程式碼實作:
下面改進的程式碼增強了可讀性並包含全面的註解:
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 }
用法範例(WinForms):
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); } }
請記得新增錯誤處理並正確處置GlobalHotkey
實例(如OnFormClosing
所示)以防止資源外洩。 此修訂後的程式碼為管理 C# WinForms 應用程式中的全域熱鍵提供了更強大且易於理解的解決方案。
以上是如何在 C# 中設定全域熱鍵以觸發應用程式事件,即使應用程式未處於焦點狀態?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文解釋了C標準模板庫(STL),重點關注其核心組件:容器,迭代器,算法和函子。 它詳細介紹了這些如何交互以啟用通用編程,提高代碼效率和可讀性t

本文詳細介紹了c中有效的STL算法用法。 它強調了數據結構選擇(向量與列表),算法複雜性分析(例如,std :: sort vs. std vs. std :: partial_sort),迭代器用法和並行執行。 常見的陷阱

本文詳細介紹了C中的有效異常處理,涵蓋了嘗試,捕捉和投擲機制。 它強調了諸如RAII之類的最佳實踐,避免了不必要的捕獲塊,並為強大的代碼登錄例外。 該文章還解決了Perf

本文討論了使用C中的移動語義來通過避免不必要的複制來提高性能。它涵蓋了使用std :: Move的實施移動構造函數和任務運算符,並確定了關鍵方案和陷阱以有效

C 20範圍通過表現力,合成性和效率增強數據操作。它們簡化了複雜的轉換並集成到現有代碼庫中,以提高性能和可維護性。

本文討論了C中的動態調度,其性能成本和優化策略。它突出了動態調度會影響性能並將其與靜態調度進行比較的場景,強調性能和之間的權衡

文章討論了在C中有效使用RVALUE參考,以進行移動語義,完美的轉發和資源管理,重點介紹最佳實踐和性能改進。(159個字符)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1
強大的PHP整合開發環境

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver Mac版
視覺化網頁開發工具