WPF TextBox 控制項擷取熱鍵並轉為 win32 Keys,wpftextbox

來源:互聯網
上載者:User

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"
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.