winform數字軟鍵盤
阿新 • • 發佈:2019-01-03
最近一個專案做的觸控式螢幕的一個應用,因為沒有鍵盤,所有需要使用軟鍵盤,雖然可以呼叫系統的軟鍵盤,但是系統軟體盤不能固定位置,即每次彈出的位置不固定,甚至有時候擋住了下一個需要輸入的文字框。其次,這個程式在螢幕是全屏顯示的,使用者不能退出這個程式,但是呼叫系統軟體盤後可以輕鬆的關閉這個程式,或者說將電腦關機重啟。因此就自己寫一個小鍵盤的程式,因為只有一個介面需要輸入,所有就直接將鍵盤嵌入到窗體中。
首先看一下測試效果圖
這裡一個有四個文字框可以接受使用者輸入,當用戶點選某一個輸入框時,就可以點選按鈕輸入相應的數字,當點選退格時逐個刪除輸入的內容。同時如果使用者發現輸入有誤時
可以再已經輸入的基礎上,在指定位置進行增加或刪除。
具體程式碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace KeyBoard { public partial class Form1 : Form { TextBox currentTextBox; int currentpos; public Form1() { InitializeComponent(); foreach (Control ctl in Controls) { if (ctl.GetType().Equals(typeof(TextBox))) ctl.LostFocus += new EventHandler(ctl_LostFocus); else if (ctl.Name == "btnKeyBoardClear") ctl.Click += new EventHandler(ctl_ClearClick); else if (ctl.GetType().Equals(typeof(Button)) && ctl.Name != "btnSubmit") ctl.Click += new EventHandler(ctl_Click); else ctl.Enter += new EventHandler(ctl_Enter); } } void ctl_ClearClick(object sender, EventArgs e) { if (currentTextBox != null) { try { currentTextBox.Text = currentTextBox.Text.Remove(currentpos - 1, 1); currentpos -= ((Button)sender).Text.Length; currentTextBox.Focus(); currentTextBox.SelectionStart = currentpos + 1; currentTextBox.SelectionLength = 0; } catch { MessageBox.Show("請從正確位置刪除!"); } } else return; } void ctl_Enter(object sender, EventArgs e) { currentTextBox = null; } void ctl_Click(object sender, EventArgs e) { if (currentTextBox != null) { currentTextBox.Text = currentTextBox.Text.Insert(currentpos, ((Button)sender).Text); currentpos += ((Button)sender).Text.Length; currentTextBox.Focus(); currentTextBox.SelectionStart = currentpos; currentTextBox.SelectionLength = 0; } else return; } void ctl_LostFocus(object sender, EventArgs e) { currentTextBox = (TextBox)sender; currentpos = currentTextBox.SelectionStart; } } }