WPF TextBox 控件获取热键并转为 win32 Keys

WPF 中使用的 Key 对象与 WinForm 中的 Keys 不同,两者的按键枚举对象与物理键的映射关系有功能键上有区别,无法进行类型强制转换。使用 win api 注册热键时,需要将之转换成 win32 的键值,可以使用 KeyInterop.VirtualKeyFromKey(),另外,Keys 可以保存组合键,Key 则只是单个按键。Keys 的成员中有个 Modifiers,从下图可以看出 0~15位之外,是用来存放功能键的。 从两张图对比上,可以直观地发现两者的区别。


示例代码:

using System.Windows.Input;

namespace demo.Controls
{
    class HotKeyTextBox : BeiLiNu.Ui.Controls.WPF.Controls.XTextBox
    {
        private System.Windows.Forms.Keys pressedKeys = System.Windows.Forms.Keys.None;
        protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            int keyValue = KeyInterop.VirtualKeyFromKey(e.Key);
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                keyValue += (int)System.Windows.Forms.Keys.Control;
            }
            if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
            {
                keyValue += (int)System.Windows.Forms.Keys.Alt;
            }
            if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
            {
                keyValue += (int)System.Windows.Forms.Keys.Shift;
            }
            
            this.Keys = (System.Windows.Forms.Keys) keyValue;

            e.Handled = true;           
        }

        public System.Windows.Forms.Keys Keys
        {
            get { return pressedKeys; }
            set
            {
                pressedKeys = value;
                setText(value);
            }
        }

        private void setText(System.Windows.Forms.Keys keys)
        {
            this.Text = keys.ToString();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章