熱鍵 (預設 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);
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);
}
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
}
}
GetForegroundWindow():取得前景視窗控制代碼GetWindowText():取得視窗標題文字