Одним из решений было бы использование взаимодействия и использование Win32 RegisterHotKey API. Вот быстрый и грязный пример, который я только что собрал, чтобы он не был хорошо протестирован, и я не уверен, что нет никаких неожиданных побочных эффектов, но он должен работать.
Во-первых, это простое HotKeyManager
, которое отвечает за основное взаимодействие, предоставляет скрытое окно для обработки собственных сообщений Windows (WM_HOTKEY), которое преобразуется в событие .NET HotKeyPressed
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class HotKeyManager
{
public static event EventHandler<HotKeyEventArgs> HotKeyPressed;
public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
{
int id = System.Threading.Interlocked.Increment(ref _id);
RegisterHotKey(_wnd.Handle, id, (uint)modifiers, (uint)key);
return id;
}
public static bool UnregisterHotKey(int id)
{
return UnregisterHotKey(_wnd.Handle, id);
}
protected static void OnHotKeyPressed(HotKeyEventArgs e)
{
if (HotKeyManager.HotKeyPressed != null)
{
HotKeyManager.HotKeyPressed(null, e);
}
}
private static MessageWindow _wnd = new MessageWindow();
private class MessageWindow : Form
{
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY)
{
HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);
HotKeyManager.OnHotKeyPressed(e);
}
base.WndProc(ref m);
}
private const int WM_HOTKEY = 0x312;
}
[DllImport("user32")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static int _id = 0;
}
public class HotKeyEventArgs : EventArgs
{
public readonly Keys Key;
public readonly KeyModifiers Modifiers;
public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
{
this.Key = key;
this.Modifiers = modifiers;
}
public HotKeyEventArgs(IntPtr hotKeyParam)
{
uint param = (uint)hotKeyParam.ToInt64();
Key = (Keys)((param & 0xffff0000) >> 16);
Modifiers = (KeyModifiers)(param & 0x0000ffff);
}
}
[Flags]
public enum KeyModifiers
{
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
NoRepeat = 0x4000
}
Ниже показано простое приложение для оконных форм, которое будет скрывать основную форму и реагировать на события горячих клавиш. Я не справлялся с закрытием приложения и отменой регистрации горячей клавиши, вы можете справиться с этим.
using System;
using System.Windows.Forms;
namespace HotKeyManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
HotKeyManager.RegisterHotKey(Keys.A, KeyModifiers.Alt);
HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
}
void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
MessageBox.Show("Hello");
}
protected override void SetVisibleCore(bool value)
{
// Quick and dirty to keep the main window invisible
base.SetVisibleCore(false);
}
}
}