Skip to main content
 首页 » 编程设计

c#之如何创建热键来显示窗口

2024年02月24日22grandyang

我正在使用 C# 开发窗口应用程序 .我想在按键时显示我的应用程序窗口,但我不知道如何创建热键..告诉我?

请您参考如下方法:

不要为此使用钩子(Hook),最好使用 RegisterHotKey和 UnregisterHotKey win32 函数:

public class YourForm : Form 
{ 
    private const int WM_HOTKEY = 0x0312; 
 
    [Flags] 
    private enum MOD : uint 
    { 
        MOD_ALT = 0x0001, 
        MOD_CONTROL = 0x0002, 
        MOD_SHIFT = 0x0004, 
        MOD_WIN = 0x0008 
    } 
 
    [DllImport("user32.dll", SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, MOD fsModifiers, uint vk); 
 
    [DllImport("user32.dll", SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id); 
 
    protected override WndProc(ref Message m) 
    { 
        if (m.Msg == WM_HOTKEY) 
        { 
            // Your code here 
        } 
    } 
}