触摸一体机没有硬件键盘,系统软键盘占面积大,位于屏幕底部,点击不是很方便。某些时候只需要输入数字,这时弹出九宫格数字键盘就足够了。
以下实现的是弹出一个弹窗作为软键盘。
创建一个窗体FrmSoftKey
,将FormBorderStyle
设置为none
,将startPosition
设置为Manual
按钮命名: 0~9
按钮分别命名为 btn_0 ~ btn_9
,-
和 .
分别命名为 btn_A
和 btn_B
,清空、删除、确定分别命名为 btnCLR
、 btnDEL
、btnENT
,
绑定事件,事件代码如下
public partial class FrmSoftKey : Form
{
public FrmSoftKey()
{
InitializeComponent();
}
private string str = "";
public string Str { get { return str; } set { str = value; Invalidate(); } }
void btn_A_Click(object sender, EventArgs e)
{
textBox1.Text += "-"; textBox1.SelectionStart = textBox1.Text.Length;
}
void btn_B_Click(object sender, EventArgs e)
{
textBox1.Text += "."; textBox1.SelectionStart = textBox1.Text.Length;
}
void btn_Click(object sender, EventArgs e)
{
Button B = (Button)sender;
textBox1.Text += B.Name.Substring(4, 1);
textBox1.SelectionStart = textBox1.Text.Length;
}
void btnCLR_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
textBox1.Text = string.Empty;
}
}
void btnDEL_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
textBox1.Focus();
textBox1.SelectionStart = textBox1.Text.Length;
}
public event EventHandler BtnTestClick;
void btnENT_Click(object sender, EventArgs e)
{
str = textBox1.Text;
textBox1.Text = "";
FrmInputDialog.Password = str;//将输入的字符串传给主窗体
this.Dispose();
this.Close();
}
}
名字和事件名对应的按钮绑定对应的 click
事件,btn_0~btn_9
的 Click
全部绑定到 btn_Click
事件
可以一次选中10个按钮,绑定 btn_Click 事件
5. 至此软键盘窗体已经设计完成,接下来是使用。
将键盘与文本框tb_pwd
绑定(该文本框位于主窗体,弹出的软键盘是个子窗体),
主窗体中添加静态变量
public static string Password { get; set; }
tb_pwd
添加MouseClick
事件,
private void tb_pwd_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
TextBox textBox = (TextBox)sender;
// 获取 TextBox 的屏幕位置
Point textboxLocation = textBox.PointToScreen(Point.Empty);
// 创建一个新的窗体
FrmSoftKey frmSoftKey = new FrmSoftKey();
frmSoftKey.Str = "";
// 计算窗体的位置
int popupX = textboxLocation.X;
int popupY = textboxLocation.Y + textBox.Height;
// 设置窗体的位置
frmSoftKey.Location = new Point(popupX, popupY);
// 显示窗体
frmSoftKey.ShowDialog();
tb_pwd.Text = Password;
Close();
}
}