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


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