WPF TextBox 控制項擷取熱鍵並轉為 win32 Keys,wpftextbox
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(); } }}
WPF 處理textbox的樣式問題,點擊獲得焦點背景顏色變化,當點擊表單其他地方(非控制項),textbox自動
背景色的變化,可以在IsFocused事件中寫。
至於輸入完成後textBox失去焦點,可以textbox接收到斷行符號按鍵事件和失去焦點這個兩個事件中,將焦點轉移到其他的Element上去。
例如
Grid.IsFocusable = true;
Grid.GetFocus();
Grid.IsFocusable = false;
WPF 中TextBox控制項的Text屬性靠右對齊
TextAlignment="Left"