实现快捷方式编辑器TextBox的最佳方法是什么?

时间:2012-02-23 17:38:28

标签: c# wpf winforms keyboard keyboard-shortcuts

我想要做的是实现一个TextBox,它接受​​一个组合键作为输入。例如,按下这些键时会出现文本Win + Ctrl + A(Windows窗体或WPF)。

一个很好的例子是Winamp设置,在“Global Hotkeys”下。

2 个答案:

答案 0 :(得分:3)

这是您可以检测几乎所有按下的键的方法: 来源:How to detect the currently pressed key?

private KeyMessageFilter m_filter = new KeyMessageFilter();

private void Form1_Load(object sender, EventArgs e)
{
    Application.AddMessageFilter(m_filter);

}


public class KeyMessageFilter : IMessageFilter
{
    private Dictionary<Keys, bool> m_keyTable = new Dictionary<Keys, bool>();

    public Dictionary<Keys, bool> KeyTable
    {
        get { return m_keyTable; }
        private set { m_keyTable = value; }
    }

    public bool IsKeyPressed()
    {
        return m_keyPressed; 
    }

    public bool IsKeyPressed(Keys k)
    {
        bool pressed = false;

        if (KeyTable.TryGetValue(k, out pressed))
        {
            return pressed;                  
        }

        return false; 
    }

    private const int WM_KEYDOWN = 0x0100;

    private const int WM_KEYUP = 0x0101;

    private bool m_keyPressed = false;


    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            KeyTable[(Keys)m.WParam] = true;

            m_keyPressed = true;
        }

        if (m.Msg == WM_KEYUP)
        {                
            KeyTable[(Keys)m.WParam] = false;

            m_keyPressed = false;
        }

        return false;
    }
}

答案 1 :(得分:0)

检查出来:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    HotKeyCls h = new HotKeyCls() { Ctrl = e.Control, Alt = e.Alt, Shift = e.Shift, Key = e.KeyCode };
    textBox1.Text = h.ToString();
}

HotKeyCls:

//Coded by Amen Ayach's DataClassBuilder @23/02/2012
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class HotKeyCls{

    private bool _Ctrl;
    public bool Ctrl{
        get {
            return _Ctrl;
        }
        set {
            _Ctrl = value;
        }
    }

    private bool _Shift;
    public bool Shift{
        get {
            return _Shift;
        }
        set {
            _Shift = value;
        }
    }

    private bool _Alt;
    public bool Alt{
        get {
            return _Alt;
        }
        set {
            _Alt = value;
        }
    }

    private System.Windows.Forms.Keys _Key;
    public System.Windows.Forms.Keys Key
    {
        get {
            return _Key;
        }
        set {
            _Key = value;
        }
    }

    public override string ToString()
    {
        return (Ctrl ? "Ctrl+" : "") + (Shift ? "Shift+" : "") + (Alt ? "Alt+" : "") + Key.ToString();           
    }
}