我在网上搜索过这个,但根本找不到任何东西。 我想要做的是创建一个键盘快捷方式,我将能够在所有应用程序中使用。一个通用键盘快捷键,所以当我按下时,在任何应用程序中说 Ctrl + Shift + X ,它会执行一段代码我在C#中创建。例如,当我在Skype中时,我会选择文本并按 Ctrl + Shift + X (或其他任何组合键),它会将文本的颜色从黑色变为蓝色。这只是尝试解释我想做什么的一个例子。我以为我必须导入一个DLL并编辑它(也许是user32.dll?)我只是在猜测。我不知道如何做到这一点,所以任何帮助将不胜感激!
提前多多感谢:)
PS:我使用的是Windows Forms Application,.NET Framework 4.0。不清楚我想做什么/说什么?请随时发表评论,我会马上回复你。
答案 0 :(得分:3)
Win32具有RegisterHotKey函数作为Win32 API的一部分。要在托管代码(C#)中使用它,您必须pInvoke它。这是一个例子:
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);
}
}
此代码来自this article。阅读该文章以获取更多信息和更多示例。