新建个winform,找到窗口事件中的KeyDown,双击添加事件。好吧不讲废话了,直接上代码
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//如果同时按下了 ctrl键和A键,弹出信息框
if (e.Control && e.KeyCode == Keys.A)
{
MessageBox.Show("害怕.jpg");
}
}
<Window.Resources>
<RoutedUICommand x:Key="I_AM_RES"/>
Window.Resources>
Modifiers 设置 Control,Alt 这样的标识键<-->
Key 设置 A,B,C ···<-->
<Window.InputBindings>
<KeyBinding Modifiers="Control" Key="A" Command="{StaticResource I_AM_RES}" />
Window.InputBindings>
将刚刚建的资源绑定事件,事件名叫KeyClick(等等还得去把这个事件给写了)<-->
<Window.CommandBindings>
<CommandBinding Command="{StaticResource I_AM_RES}" Executed="KeyClick"/>
Window.CommandBindings>
private void KeyClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("害怕[WPF限定版].jpg");
}
设置全局热键要用到 user32.dll 中的 RegisterHotKey 函数和 UnregisterHotKey 函数,这里借用一下我搜到的大佬借用的网上大佬的代码(感谢大佬们!!)
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class SystemHotKey
{
///
/// 如果函数执行成功,返回值不为0。
/// 如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。
///
/// 要定义热键的窗口的句柄
/// 定义热键ID(不能与其它ID重复)
/// 标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
/// 定义热键的内容
///
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
///
/// 注销热键
///
/// 要取消热键的窗口的句柄
/// 要取消热键的ID
///
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
///
/// 辅助键名称。
/// Alt, Ctrl, Shift, WindowsKey
///
[Flags()]
public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 }
///
/// 注册热键
///
/// 窗口句柄
/// 热键ID
/// 组合键
/// 热键
public static void RegHotKey(IntPtr hwnd, int hotKeyId, KeyModifiers keyModifiers, Keys key)
{
if (!RegisterHotKey(hwnd, hotKeyId, keyModifiers, key))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 1409)
{
MessageBox.Show("热键被占用 !");
}
else
{
MessageBox.Show("注册热键失败!错误代码:" + errorCode);
}
}
}
///
/// 注销热键
///
/// 窗口句柄
/// 热键ID
public static void UnRegHotKey(IntPtr hwnd, int hotKeyId)
{
//注销指定的热键
UnregisterHotKey(hwnd, hotKeyId);
}
}
原帖-博客园-小浩叔叔-C# 注册 Windows 热键
值得注意的是,这里有个窗口句柄(IntPtr hwnd)的参数,winform和wpf的获取方法又是不一样的
IntPtr intPtr = this.Handle;
IntPtr intPtr = (new WindowInteropHelper(this)).Handle;