首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual C# 彈出視窗攔截器(四):系統熱鍵註冊與 WndProc 訊息處理完整實作

     編輯:關於C語言

系統熱鍵應用價值

熱鍵 (預設 Ctrl+Shift+J) 讓使用者無需切換至主視窗即可觸發攔截功能,提升使用體驗。

熱鍵註冊核心程式碼

public void SetHotKey(Keys key, bool ctrl, bool shift, bool alt, bool win)
{
    m_hotkey = key;
    m_ctrlhotkey = ctrl;
    m_shifthotkey = shift;
    m_althotkey = alt;
    m_winhotkey = win;

    KeyModifiers modifiers = KeyModifiers.None;
    if (m_ctrlhotkey) modifiers |= KeyModifiers.Control;
    if (m_shifthotkey) modifiers |= KeyModifiers.Shift;
    if (m_althotkey) modifiers |= KeyModifiers.Alt;
    if (m_winhotkey) modifiers |= KeyModifiers.Windows;

    NativeWIN32.RegisterHotKey(Handle, 100, modifiers, m_hotkey);
}

標準熱鍵註冊流程

// Form.Load 中註冊
bool success = RegisterHotKey(Handle, 100, 
    KeyModifiers.Control | KeyModifiers.Shift, Keys.J);

// Form.Closing 中註銷
UnregisterHotKey(Handle, 100);

WndProc 訊息攔截

protected override void WndProc(ref Message m)
{
    const int WM_HOTKEY = 0x0312;
    switch (m.Msg)
    {
        case WM_HOTKEY:
            MessageBox.Show("熱鍵被按下");
            ProcessHotkey();
            break;
    }
    base.WndProc(ref m);
}

NativeWIN32 封裝類別

public class NativeWIN32
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, 
        KeyModifiers fsModifiers, Keys vk);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    [Flags]
    public enum KeyModifiers
    {
        None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8
    }
}

熱鍵觸發處理邏輯

protected void ProcessHotkey()
{
    IntPtr hwnd = NativeWIN32.GetForegroundWindow();
    if (!hwnd.Equals(IntPtr.Zero))
    {
        NativeWIN32.STRINGBUFFER title;
        NativeWIN32.GetWindowText(hwnd, out title, 256);
        if (title.szText.Length > 0)
            AddWindowTitle(title.szText);  // 加入 ListView
    }
}

關鍵 API 串聯

  1. GetForegroundWindow():取得前景視窗控制代碼
  2. GetWindowText():取得視窗標題文字
  3. 比對標題關鍵字決定是否攔截關閉
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved