使用 System.Windows.Forms.Timer 创建一个简单的计时工具。
本文向读者展示了如何使用基本的 C# 2.0 WinForms 创建一个可用的应用程序。
引言
在本文中,我们将学习如何使用 System.Windows.Forms.Timer 和 System.IO 命名空间中的文件 IO,来创建一个用于跟踪时间的应用程序。该应用程序的目标是:1. 允许用户准确跟踪在不同任务上花费的时间。 2. 易于使用和部署。

使用代码
我们需要一个时钟来显示在任务上花费的时间量。为此,我们需要一个计时器。计时器对象将在指定的间隔处引发一个事件。我们可以使用它来更新时钟,使其每秒更新一次。我们将以下代码放入窗体的加载方法中来设置它
设置计时器
// Create timer, set interval to 1 second (1000 ms), add event and create eventhandler. tmrDigitalClock = new System.Windows.Forms.Timer(); tmrDigitalClock.Enabled = true; tmrDigitalClock.Interval = 1000; tmrDigitalClock.Tick += new System.EventHandler(tmrDigitalClock_Tick); //Next we add code to handle the event: private void tmrDigitalClock_Tick(object sender, System.EventArgs e) { if (starttime != System.DateTime.MinValue) { stoptime = DateTime.Now; System.TimeSpan duration = stoptime.Subtract(starttime); lblTime.Text = ReadableDuration(duration); } }
我们使用此方法来告诉时钟更改标签,指示当前在任务上花费的时间。变量 starttime 和 stoptime 是 System.DataTime 变量。当用户点击“开始”按钮时,starttime 变量设置为 System.DateTime.Now,否则设置为 System.DateTime.MinValue。我们通过从当前时间中减去任务开始的时间来计算持续时间,并相应地更新标签。
设置 UI 事件以启动和停止计时器。
接下来,我们添加两个按钮来开始和停止时间跟踪。对于“开始”按钮,我们添加以下方法来处理单击事件
private void Start_Click(object sender, EventArgs e) { // Disable the type box and the text field. if (cboTimeCode.SelectedIndex < 0) { MessageBox.Show("Must select a code."); return; } // Make UI read only for the duration. cboTimeCode.Enabled = false; txtTicket.Enabled = false; Start.Enabled = false; Stop.Enabled = true; // Set the start time. starttime = DateTime.Now; }
对于“停止”按钮,我们添加以下方法来处理单击事件。此方法计算在任务上花费的时间量,并将其保存到文件中。
private void Stop_Click(object sender, EventArgs e) { stoptime = DateTime.Now; System.TimeSpan duration = stoptime.Subtract(starttime); starttime = System.DateTime.MinValue; // Have to have this at the end in case you leave app open for more than a day. today = DateTime.Now; // Write to the file. TextWriter tw = File.AppendText(datafile); // Date, Category, ticket number, duration. tw.WriteLine(today.ToString("M/d/yyyy") + delimiter + cboTimeCode.SelectedItem + delimiter + txtTicket.Text + delimiter + DurationMinutes(duration)); // Make sure to close the file. tw.Close(); // Refresh the UI. cboTimeCode.Enabled = true; txtTicket.Enabled = true; cboTimeCode.SelectedIndex = -1; txtTicket.Text = null; lblTime.Text = "00:00:00"; Start.Enabled = true; Stop.Enabled = false; }
读取文件。
现在我们已经将数据存储在文件中,我们想使用它。在我们的例子中,我们将从文件中读取数据,然后将其显示在 DataGridView 中。在这个应用程序中,当用户想要查看给定日期范围内的数据时,他们会输入该日期范围,然后点击“全部”按钮。当用户这样做时,我们从文件中读取数据,将其加载到 DataTable 中,然后将我们的 DataGridView 绑定到填充的 DataTable。
private void PopulateTable(DataTable dtDataTable) { string contents; int tabSize = 4; string[] arInfo; string line; DataRow row; try { string FILENAME = datafile; StreamReader objStreamReader; objStreamReader = File.OpenText(FILENAME); while ((line = objStreamReader.ReadLine()) != null) { contents = line; char[] textdelimiter = { '^' }; arInfo = contents.Split(textdelimiter); for (int i = 0; i <= arInfo.Length; i++) { row = dtDataTable.NewRow(); if ((i < arInfo.Length) && (arInfo[i].ToString() != null)) { row["Date"] = DateTime.Parse(arInfo[0].ToString()); } if (i + 1 < arInfo.Length) { row["Code"] = arInfo[1].ToString(); } if (i + 2 < arInfo.Length) { row["Ticket"] = arInfo[2].ToString(); } if(i + 3 < arInfo.Length) { double dbDuration = Double.Parse(arInfo[3].ToString()); string strDuration = string.Format("{0:F2}", dbDuration); row["Duration in minutes"] = strDuration; dtDataTable.Rows.Add(row); } i = i + 2; } } objStreamReader.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
关注点
在这个应用程序中,我们使用了计时器来更新标签并创建一个功能性的数字时钟。在实践中,您可能会想到使用这个简单但强大的工具的无数种方法,例如定期提示用户,或定期检查环境中的新信息。
历史
初始修订版。