最近要做一个winform窗体热键隐藏的程序,在网上搜了很多这样的代码,自己整理了一个比较简洁的:
热键隐藏
1
using System.Runtime.InteropServices;
2![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
Boolean hide = true;
4![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
[DllImport("user32.dll", SetLastError = true)] //导入注册函数
6
public static extern bool RegisterHotKey(
7
IntPtr hWnd, // handle to window
8
int id, // hot key identifier
9
KeyModifiers fsModifiers, // key-modifier options
10
Keys vk // virtual-key code
11
);
12![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
13
[DllImport("user32.dll", SetLastError = true)]
14
public static extern bool UnregisterHotKey(
15
IntPtr hWnd, // handle to window
16
int id // hot key identifier
17
);
18![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
19![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
20
[Flags()]
21
public enum KeyModifiers
22![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
23
None = 0,
24
Alt = 1,
25
Control = 2,
26
Shift = 4,
27
Windows = 8
28
}
29
private void Form1_Load(object sender, EventArgs e)
30![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
31
RegisterHotKey(Handle, 100, 0, Keys.F10);//窗体载入时注册热键
32
}
33![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
34
protected override void WndProc(ref Message m)//监视Windows消息
35![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
36
const int WM_HOTKEY = 0x0312;//按快捷键
37
switch (m.Msg)
38![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
39
case WM_HOTKEY:
40
this.menuItem10.PerformClick(); //调用主处理程序
41
break;
42
}
43
base.WndProc(ref m);
44
}
45![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
46
private void menuItem10_Click(object sender, EventArgs e)
47![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
48
49
if (hide == true)
50![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
51
this.ShowInTaskbar = false;
52
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
53
hide = false;
54
}
55
else
56![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
57
this.ShowInTaskbar = true;
58
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
59
hide = true;
60
61
}
62
}
以上代码按下F10键能够将窗体隐藏,但隐藏后再无法调出,按下alt+tab能调出,可是再按F10键就再也无法隐藏了,不知道问题在哪里?哪位大侠指点一下。