winform数字软键盘

来源:互联网 发布:java jsonobject jar 编辑:程序博客网 时间:2024/05/16 17:25

最近一个项目做的触摸屏的一个应用,因为没有键盘,所有需要使用软键盘,虽然可以调用系统的软键盘,但是系统软件盘不能固定位置,即每次弹出的位置不固定,甚至有时候挡住了下一个需要输入的文本框。其次,这个程序在屏幕是全屏显示的,用户不能退出这个程序,但是调用系统软件盘后可以轻松的关闭这个程序,或者说将电脑关机重启。因此就自己写一个小键盘的程序,因为只有一个界面需要输入,所有就直接将键盘嵌入到窗体中。

首先看一下测试效果图

这里一个有四个文本框可以接受用户输入,当用户点击某一个输入框时,就可以点击按钮输入相应的数字,当点击退格时逐个删除输入的内容。同时如果用户发现输入有误时

可以再已经输入的基础上,在指定位置进行增加或删除。

具体代码如下:

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


 

1 0
原创粉丝点击