用Visual C#.net完成一个简单时间提醒器
有些人一用起电脑就会忘记时间,所以我就想做一个小工具,能实现闹钟的功能。
首先,要设计用户界面,要简介易用,所以不必太多的东西,要两个TextBox,两个Button,还有几个用来显示文字提示Lable,的就可以了!
把控件安排好以后,就可以编写代码了。其中一个TextBox(代码中的textBox1)是要输入时间到了以后要显示的提示信息。另一个TextBox则是设置时间的(代码中的textBox2)。设置时间的TextBox的格式是“00:00:00”,所以要有很多限定,比如只能输入数字,而且其中的两个冒号不能被修改。一下我就设计了SimpleTextBox类,来限制时间的输入。SimpleTextBox类代码如下:
文件:SimpleTextBox.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace SimpleTextBox
{
public class SimpleTextBox : System.Windows.Forms.TextBox
{
private string m_format; //设定时间的显示格式
private char m_inpChar; //缺省的字符
public SimpleTextBox()
{
base.Multiline=false;
base.MaxLength=8;
m_inpChar = '0';
m_format = "00:00:00";
}
private bool IsValidChar(char input)
{
return(char.IsDigit(input)); //检查是否为数字
}
//重载TextBox的OnKeyPress方法
protected override void OnKeyPress(KeyPressEventArgs e)
{
int strt = base.SelectionStart;
int len = base.SelectionLength;
int p;
// 处理Backspace键 -> 用缺省字符代替删除后的地方
if(e.KeyChar == 0x08)
{
string s = base.Text;
p = Prev(strt);
if(p != strt)
{
base.Text = s.Substring(0, p) +m_inpChar.ToString() + s.Substring(p + 1);
base.SelectionStart = p;
base.SelectionLength = 1;
}
e.Handled = true;
return;
}
// 初始显示
if(m_format[strt] != m_inpChar)
{
strt = Next(-1);
len = 1;
}
// 接受键盘的输入
if(IsValidChar(e.KeyChar))
{
string t = "";
t = base.Text.Substring(0, strt);
t += e.KeyChar.ToString();
if(strt + len != base.MaxLength)
{
t += m_format.Substring(strt + 1, len - 1);
t += base.Text.Substring(strt + len);
}
else
t += m_format.Substring(strt + 1);
base.Text = t;
// 下一个输入字符
strt = Next(strt);
base.SelectionStart = strt;
//m_caret = strt;
base.SelectionLength = 1;
}
e.Handled = true;
}
//将光标向前检测
private int Prev(int startPos)
{
int strt = startPos;
int ret = strt;
while(strt > 0)
{
strt--;
if(m_format[strt] == m_inpChar)
return strt;
}
return ret;
}
//将光标向后检测,返回下一个字符的位置
private int Next(int startPos)
{
int strt = startPos;
int ret = strt;
while(strt < base.MaxLength - 1)
{
strt++;
if(m_format[strt] == m_inpChar)
return strt;
}
return ret;
}
//重载OnMouseUp事件
protected override void OnMouseUp(MouseEventArgs e)
{
int strt = base.SelectionStart;
int orig = strt;
int len = base.SelectionLength;
//重设定开始位置
if(strt == base.MaxLength || m_format[strt] != m_inpChar)
{
// reset start
if(Next(strt) == strt)
strt = Prev(strt);
else
strt = Next(strt);
base.SelectionStart = strt;
}
// 重设定选定长度
if(len < 1)
base.SelectionLength = 1;
else if(m_format[orig + len - 1] != m_inpChar)
{
len += Next(strt + len) - (strt + len);
base.SelectionLength = len;
}
base.OnMouseUp(e);
}
}
}
可以将这个类编译为一个控件,以后可以继续使用。
下面是TimerAlarm类,这个类使用了一个Timer类来进行计时,并在时间到的时候发出提示。代码如下:
using System;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
public class TimerAlarm
{
private int clockTime=0;
private int alarmTime = 0;
private string message="时间到了";
private System.Timers.Timer timerClock = new System.Timers.Timer();
public int AlarmTime
{
set
{
alarmTime=value;
}
}
public int ClockTime
{
set
{
clockTime=value;
}
}
public string Message
{
set
{
message=value;
}
}
public int Countdown
{
get
{
return alarmTime - clockTime;
}
}
public TimerAlarm()
{
//MessageBox.Show("TimeAlarm start.");
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
}
public void OnTimer( Object source, ElapsedEventArgs e )
{
try
{
clockTime++;
if( clockTime == alarmTime )
{
MessageBox.Show(message,"时间到了",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
catch( Exception ex )
{
MessageBox.Show("OnTimer(): " + ex.Message );
}
}
public void StopTimer()
{
timerClock.Enabled=false;
}
}
然后用了FormatConvert类,它提供了两个静态的方法,inputToSeconds()将一个string型的时间字串转换成一共有多少秒。
public static int inputToSeconds( string timerInput )
{
string[] timeArray = new string[3];
int minutes = 0;
int hours = 0;
int seconds = 0;
int occurence = 0;
int length = 0;
int totalTime=0;
occurence = timerInput.LastIndexOf(":");
length = timerInput.Length;
//Check for invalid input
if( occurence == -1 || length != 8 )
{
MessageBox.Show("Invalid Time Format.");
}
else
{
timeArray = timerInput.Split(':');
seconds = Convert.ToInt32( timeArray[2] );
minutes = Convert.ToInt32( timeArray[1] );
hours = Convert.ToInt32( timeArray[0] );
totalTime += seconds;
totalTime += minutes*60;
totalTime += (hours*60)*60;
}
return totalTime;
}
secondsToTime方法是把秒转换一个时间格式的字串返回。
public static string secondsToTime( int seconds )
{
int minutes = 0;
int hours = 0;
while( seconds >= 60 )
{
minutes += 1;
seconds -= 60;
}
while( minutes >= 60 )
{
hours += 1;
minutes -= 60;
}
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
string strSeconds = seconds.ToString();
if( strHours.Length < 2 )
strHours = "0" + strHours;
if( strMinutes.Length < 2 )
strMinutes = "0" + strMinutes;
if( strSeconds.Length < 2 )
strSeconds = "0" + strSeconds;
return strHours + ":" + strMinutes + ":" + strSeconds;
}
下面就是主窗体了,分别编写两个按钮的事件:
开始按钮:
private void button1_Click(object sender, System.EventArgs e)
{
timeAlarm=new TimerAlarm();
timeAlarm.AlarmTime=FormatConvert.inputToSeconds(this.textBox2.Text);
timeAlarm.Message=this.textBox1.Text;
if(timeAlarm.Countdown>0)
this.timer1.Enabled=true;
if(textBox2.Text!="00:00:00")
this.textBox2.ReadOnly=true;
}
建立一个TimerAlarm的实例,开始计时。
重设按钮:
private void button2_Click(object sender, System.EventArgs e)
{
this.textBox1.Clear();
this.timer1.Enabled=false;
if(timeAlarm!=null)
timeAlarm.StopTimer();
this.textBox2.ReadOnly=false;
this.textBox2.Text = "00:00:00";
}
恢复程序。
还有一个Timer,用来动态显示剩下的时间。
private void timer1_Tick(object sender, System.EventArgs e)
{
if(timeAlarm.Countdown>=0)
textBox2.Text=FormatConvert.secondsToTime(timeAlarm.Countdown);
else
{
this.timer1.Enabled=false;
this.textBox2.ReadOnly=false;
}
}
程序基本上已经完成了。有兴趣的朋友还可以加入系统托盘等的功能。
第一次写这种文章,时间也比较仓促,希望大家多提意见。
(参考资料:C# MaskedEdit Control ---- Oscar Bowyer, Use a timer to create a simple alarm application ---- Andrew Boisen, from CodiProject.Com)