如何创建通用键盘快捷键
本文关键字:通用键盘 快捷键 创建 何创建 | 更新日期: 2023-09-27 18:05:52
我已经在网上搜索了这个,但根本找不到任何东西。我想做的是创建一个键盘快捷键,我将能够在所有的应用程序中使用。一个通用的键盘快捷键,当我在任何应用程序中按下Ctrl+Shift+X时,它将执行我在c#中创建的一段代码。例如,当我在Skype时,我会选择文本并按Ctrl+Shift+X(或任何其他键组合),它会改变文本的颜色从黑色到蓝色。这只是一个例子,用来解释我想做什么。我想我必须导入一个DLL并编辑它(也许是user32.dll?)我只是猜测。我不知道如何做到这一点,所以任何帮助将非常感激!
提前感谢:)
PS:我使用的是Windows Forms Application, . net Framework 4.0。不清楚我想做/说什么?请随时评论,我会马上回复你。Win32有一个RegisterHotKey函数作为Win32 API的一部分。要在托管代码(c#)中使用它,您必须调用它。下面是一个例子:
public class WindowsShell
{
#region fields
public static int MOD_ALT = 0x1;
public static int MOD_CONTROL = 0x2;
public static int MOD_SHIFT = 0x4;
public static int MOD_WIN = 0x8;
public static int WM_HOTKEY = 0x312;
#endregion
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static int keyId;
public static void RegisterHotKey(Form f, Keys key)
{
int modifiers = 0;
if ((key & Keys.Alt) == Keys.Alt)
modifiers = modifiers | WindowsShell.MOD_ALT;
if ((key & Keys.Control) == Keys.Control)
modifiers = modifiers | WindowsShell.MOD_CONTROL;
if ((key & Keys.Shift) == Keys.Shift)
modifiers = modifiers | WindowsShell.MOD_SHIFT;
Keys k = key & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
keyId = f.GetHashCode(); // this should be a key unique ID, modify this if you want more than one hotkey
RegisterHotKey((IntPtr)f.Handle, keyId, (uint)modifiers, (uint)k);
}
private delegate void Func();
public static void UnregisterHotKey(Form f)
{
try
{
UnregisterHotKey(f.Handle, keyId); // modify this if you want more than one hotkey
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
public partial class Form1 : Form, IDisposable
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Keys k = Keys.A | Keys.Control;
WindowsShell.RegisterHotKey(this, k);
}
// CF Note: The WndProc is not present in the Compact Framework (as of vers. 3.5)! please derive from the MessageWindow class in order to handle WM_HOTKEY
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WindowsShell.WM_HOTKEY)
this.Visible = !this.Visible;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
WindowsShell.UnregisterHotKey(this);
}
}
这段代码来自本文。阅读那篇文章以获得更多信息和示例。