[DllImport(“user32.dll”)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport(“user32.dll”)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll")]
private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const int SWP_SHOWWINDOW = 0x0040;
private const Int32 MY_HOTKEYID = 0x9999;
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
IntPtr handle = new WindowInteropHelper(this).Handle;
RegisterHotKey(handle, MY_HOTKEYID, 0, 0x72);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
}
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle)
{
//Debug.WriteLine("hwnd:{0},msg:{1},wParam:{2},lParam{3}:,handle:{4}"
// ,hwnd,msg,wParam,lParam,handle);
if (wParam.ToInt32() == MY_HOTKEYID)
{
// 全局快捷键要执行的命令//F3
;
IntPtr handle1 = new WindowInteropHelper(this).Handle;
// SetWindowPos(handle1, HWND_TOPMOST, 0, 0, 100, 200, SWP_SHOWWINDOW);
SetWindowPos(handle1, HWND_TOPMOST, 0, 0, 0, 0, 0x4000 | 0x0001 | 0x0002);
this.WindowState = WindowState.Normal;
MessageBox.Show("Hello~~~~");
}
return IntPtr.Zero;
}
using System.Runtime.InteropServices;
using System.Windows.Input;
private const int MOD_ALT = 0x0001;
private const int MOD_CONTROL = 0x0002;
private const int MOD_SHIFT = 0x0004;
private const int MOD_WIN = 0x0008;
private const int WM_HOTKEY = 0x0312;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
IntPtr handle = new WindowInteropHelper(this).Handle;
HwndSource source = HwndSource.FromHwnd(handle);
source.AddHook(HwndHook);
RegisterHotKey(handle, 11, MOD_CONTROL | MOD_SHIFT, KeyInterop.VirtualKeyFromKey(Key.A));
RegisterHotKey(handle, 12, MOD_CONTROL | MOD_SHIFT, KeyInterop.VirtualKeyFromKey(Key.B));
}
private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY)
{
// 处理热键触发事件
// 在这里执行你想要的操作
if (wParam.ToInt32() == 11)
{
MessageBox.Show("热键触发11!");
}
handled = true;
if (wParam.ToInt32() == 12)
{
MessageBox.Show("热键触发12!");
}
handled = true;
}
return IntPtr.Zero;
}