如何实现快捷键功能
问题是基于C#代码的,不知道发在哪里,就放在这个版块了。要求实现全局快捷键,而且是单键,不是组合键。比如Space、A-Z等等。
1.非全局的组合快捷键(实现方法参见:http://blog.)
2.非全局单键(不知道怎么实现)
3.全局组合键(同样参见上链接)
4.全局单键(我的问题)
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas." xmlns:x="http://schemas." xmlns:d="http://schemas." xmlns:mc="http://schemas." xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" WindowStartupLocation="CenterScreen" KeyDown="Window_KeyDown" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="139,87,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/> <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="194,175,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_KeyDown(object sender, KeyEventArgs e) { textBlock.Text = e.Key.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Hangman_Steven { class HotKey { //如果函数执行成功,返回值不为0。 //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。 [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey( IntPtr hWnd, //要定义热键的窗口的句柄 int id, //定义热键ID(不能与其它ID重复) KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效 Keys vk //定义热键的内容 ); [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey( IntPtr hWnd, int id, Keys vk ); [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey( IntPtr hWnd, //要取消热键的窗口的句柄 int id //要取消热键的ID ); //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值) [Flags()] public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 } } }
HotKey.RegisterHotKey(Handle, 101, HotKey.KeyModifiers.Shift, Keys.A);//定义Shift+A
HotKey.RegisterHotKey(Handle, 101, Keys.A);
HotKey.RegisterHotKey(Handle, 101, Keys.A);
/// 监视Windows消息,重载WndProc方法,用于实现热键响应 protected override void WndProc(ref Message m) { const int WM_HOTKEY = 0x0312; //按快捷键 switch (m.Msg) { case WM_HOTKEY: switch (m.WParam.ToInt32()) { case 101: //这里写具体的函数内容 break;