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

C# 實作彈出視窗殺手(下):系統熱鍵註冊與前景視窗處理

     編輯:VC++

熱鍵註冊與解除

預設熱鍵 Ctrl+Shift+J,於表單載入時註冊,關閉時解除:

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

// Form Closing
UnregisterHotKey(this.Handle, 100);

熱鍵處理流程

  1. 取得前景視窗控制碼 GetForegroundWindow()。
  2. 擷取視窗標題 GetWindowText()。
  3. 若標題符合黑名單規則,加入列表或直接關閉。

程式碼實作

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

// WndProc 攔截 WM_HOTKEY
protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x0312) // WM_HOTKEY
        ProcessHotkey();
    base.WndProc(ref m);
}

P/Invoke 補充

public class NativeWIN32
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id,
        uint fsModifiers, uint vk);

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

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetForegroundWindow();

    // STRINGBUFFER、GetWindowText、SendMessage 同前文
}

小結

結合定時自動掃描與熱鍵手動觸發,構成完整的彈出視窗攔截方案。熱鍵機制亦可應用於其他需全域快速啟動功能的工具程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved