C# 时间格式的TextBox控件代码
作者:肖肖源代码:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;namespace TimeTextBoxControl
{
public partial class TimeTextBoxControl : UserControl
{
public TimeTextBoxControl()
{
InitializeComponent();
if (textBox1.Text.Equals(""))
{
textBox1.Text = "00:00";
}
}public string TimeText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
timeFormat(sender, e);
string currStr1 = "";
string currstr2 = "";
int index = textBox1.SelectionStart;//获取光标位置
if (e.KeyChar >= 48 && e.KeyChar <= 57)//判断所输入的是数字还是其他字符
{
if (index>=0 && index<5)//判断光标位置
{
if (textBox1.SelectionStart == 2)
{
currStr1 = textBox1.Text.Substring(0, index) + ":";
currstr2 = textBox1.Text.Substring(index + 2);
index++;
}
else
{
currStr1 = textBox1.Text.Substring(0, index);
currstr2 = textBox1.Text.Substring(index + 1);
}
textBox1.Text = currStr1 + e.KeyChar.ToString() + currstr2;
}
textBox1.SelectionStart = index + 1;
}
else
{
e.KeyChar = Convert.ToChar(0);
}
if (textBox1.Text.Length >= 5)
{
e.KeyChar = Convert.ToChar(0);
}
}
//判断输入的时间是否为24小时制
private void timeFormat(object sender, KeyPressEventArgs e)
{
if (textBox1.SelectionStart == 0)
{
if (e.KeyChar < 48 || e.KeyChar > 50)
{
e.KeyChar = Convert.ToChar(48);
}
}
if (textBox1.SelectionStart == 1)
{
if ((textBox1.Text.Substring(0, 1).Equals("0")))
{
if (e.KeyChar < 48 || e.KeyChar > 57)
{
e.KeyChar = Convert.ToChar(0);
}
}
else
{
if (e.KeyChar < 48 || e.KeyChar > 52)
{
e.KeyChar = Convert.ToChar(0);
补充:软件开发 , C# ,
上一个:C#操作mpp文件代码参考
下一个:C#中隐式操作CMD命令行窗口