看到在您的函数中使用 KeyPressedEventArgs 看起来真的很奇怪。热键可以通过 P/Invoking RegisterHotKey() API 函数来实现。当按下热键时,它会向您的窗口发送一条消息。这是一个在启动时不可见的表单示例,当您按下热键时会活跃起来。Ctrl+Alt+U 在这种情况下:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
private const int MYKEYID = 0; // In case you want to register more than one...
public Form1() {
InitializeComponent();
this.FormClosing += (s, args) => UnregisterHotKey(this.Handle, MYKEYID);
}
protected override void SetVisibleCore(bool value) {
if (value && !this.IsHandleCreated) {
this.CreateHandle();
RegisterHotKey(this.Handle, MYKEYID, MOD_CONTROL + MOD_SHIFT, Keys.U);
value = false;
}
base.SetVisibleCore(value);
}
protected override void WndProc(ref Message m) {
if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == MYKEYID) {
this.Visible = true;
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
SetForegroundWindow(this.Handle);
}
base.WndProc(ref m);
}
// P/Invoke declarations
private const int WM_HOTKEY = 0x312;
private const int MOD_ALT = 1;
private const int MOD_CONTROL = 2;
private const int MOD_SHIFT = 4;
[DllImport("user32.dll")]
private static extern int RegisterHotKey(IntPtr hWnd, int id, int modifier, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
}
}
请注意, SetForegroundWindow() 函数是问题,可能也是您在问题中描述的问题的根源。当用户正在使用另一个窗口时,Windows 不允许应用程序将窗口推到用户面前。在允许窗口窃取焦点之前,必须至少有几秒钟的不活动状态。使用给定的代码,很容易看到,表单的任务栏按钮将闪烁。避免将 ShowInTaskbar 属性设置为 false。使用此代码没有必要这样做,任务栏按钮在按下热键之前不会显示。