You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.9 KiB
C#
66 lines
1.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Forms;
|
|
|
|
namespace Rs.Framework
|
|
{
|
|
/// <summary>
|
|
/// 热键管理类
|
|
/// </summary>
|
|
public class HotKeyManager
|
|
{
|
|
private const int MOD_ALT = 0x0001; // Alt键
|
|
private const int MOD_CTRL = 0x0002; // Ctrl键
|
|
private const int MOD_SHIFT = 0x0004; // Shift键
|
|
private const int MOD_WIN = 0x0008; // Windows键
|
|
private const int WM_HOTKEY = 0x0312;
|
|
|
|
private Action<object, EventArgs> hotkeyAction;
|
|
private int id;
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, Keys vk);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
|
|
|
|
public HotKeyManager(Keys key, int modifier, Action<object, EventArgs> action)
|
|
{
|
|
hotkeyAction = action;
|
|
id = this.GetHashCode();
|
|
|
|
RegisterHotKey(Application.OpenForms[0].Handle, id, modifier, key);
|
|
Application.AddMessageFilter(new MessageFilter(this));
|
|
}
|
|
|
|
public void Unregister()
|
|
{
|
|
UnregisterHotKey(Application.OpenForms[0].Handle, id);
|
|
}
|
|
|
|
private class MessageFilter : IMessageFilter
|
|
{
|
|
private HotKeyManager hotkey;
|
|
|
|
public MessageFilter(HotKeyManager hotkey)
|
|
{
|
|
this.hotkey = hotkey;
|
|
}
|
|
|
|
public bool PreFilterMessage(ref Message m)
|
|
{
|
|
if (m.Msg == WM_HOTKEY && (int)m.WParam == hotkey.id)
|
|
{
|
|
hotkey.hotkeyAction(null, EventArgs.Empty);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|