winform数字软键盘

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

首先看一下测试效果图

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

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

具体代码如下:

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


 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值