最近遇到一個(gè)問題,在一個(gè)WinForm窗口中,按ALT+Z能夠?qū)崿F(xiàn)最小化到托盤及從托盤回復(fù)正常窗口。
剛開始,試著在窗口的KeyPress事件中添加,但是當(dāng)窗口最小化到托盤后,焦點(diǎn)已經(jīng)不在窗口上了,因此將不能捕捉鍵盤按鍵按下的事件,因此不能從托盤彈出。經(jīng)測(cè)試,這種方法是錯(cuò)誤的。
既然KeyPress事件不能解決問題,那么為什么不能添加熱鍵呢?
添加熱鍵的方法是
BOOL RegisterHotKey(
HWND hWnd,
int id,
UINT fsModifiers,
UINT vk
);
其中參數(shù)hWnd是注冊(cè)熱鍵的窗口句柄,id是熱鍵的標(biāo)識(shí)符,fsModifiers是在創(chuàng)建WM_HOTKEY消息時(shí)必須跟用戶定義的按鍵一同按下的特殊組合鍵,他的值為:
Value |
Description |
MOD_ALT |
Either ALT key must be held down. |
MOD_CONTROL |
Either CTRL key must be held down. |
MOD_KEYUP |
Both key up events and key down events generate a WM_HOTKEY message. |
MOD_SHIFT |
Either SHIFT key must be held down. |
MOD_WIN |
Either WINDOWS key was held down. These keys are labeled with the Microsoft Windows logo. |
我們可以使用這個(gè)函數(shù)注冊(cè)我們的熱鍵。
在C#中使用這個(gè)函數(shù),我們必須從user32.dll中將此函數(shù)導(dǎo)入,而且必須重寫WndProc函數(shù)來捕捉熱鍵消息。
以下為示例代碼:
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

private void Form1_Load(object sender, EventArgs e)

{
RegisterHotKey(this.Handle, 888, 1, Keys.Z);
this.Hide();
this.ShowInTaskbar = true;
this.comboBox1.SelectedIndex = 0;
}

protected override void WndProc(ref Message m)

{
switch (m.Msg)

{
case 0x0312:
if (m.WParam.ToString().CompareTo("888") == 0)

{
if (bIsShowed)

{
this.Hide();
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Minimized;
this.notifyIcon1.Visible = true;
this.bIsShowed = false;
}
else

{
this.Visible = true;
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Normal;
this.Activate();
this.notifyIcon1.Visible = false;
bIsShowed = true;
}
UnregisterHotKey(this.Handle, 888);
RegisterHotKey(this.Handle, 888, 1, Keys.Z);
}
break;
default:
break;
}

base.WndProc(ref m);
}