簡體   English   中英

如何創建通用鍵盤快捷鍵?

[英]How to create a universal keyboard shortcut?

我在網上搜索過這個,但根本找不到任何東西。 我想要做的是創建一個鍵盤快捷方式,我將能夠在所有應用程序中使用。 一個通用的鍵盤快捷鍵,所以當我按下時,在任何應用程序中說Ctrl + Shift + X ,它將執行我在C#中創建的一段代碼。 例如,當我在Skype時,我會選擇文本並按Ctrl + Shift + X (或任何其他組合鍵),它會將文本的顏色從黑色更改為藍色。 這只是嘗試解釋我想做什么的一個例子。 我想我必須導入一個DLL並編輯它(也許是user32.dll?)我只是在猜測。 我不知道如何做到這一點,所以任何幫助將不勝感激!

非常感謝提前:)

PS:我使用的是Windows Forms Application,.NET Framework 4.0。 不清楚我想做什么/說什么? 請隨時發表評論,我會立即回復您。

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);
    }
}

此代碼來自本文 閱讀該文章以獲取更多信息和更多示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM