假设我有两种形式。第一个将包含开始按钮,另一个是停止按钮。有没有一种方法可以确定按下开始和停止按钮之间经过的时间并以第二种形式显示。
我试过这样做并得到这些代码
形式一:开始按钮
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public DateTime startTime2;
public DateTime endTime;
public TimeSpan ts_timeElapsed;
public string s_timeElapsed;
public Form1()
{
InitializeComponent();
}
private void StartButton_Click(object sender, EventArgs e)
{
startTime2 = DateTime.Now;
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
private void Button2_Click(object sender, EventArgs e)
{
Instructions frm = new Instructions();
frm.Show();
this.Hide();
}
}
}
形式 2:停止按钮
namespace WindowsFormsApplication1
{
public partial class RoadSign1Meaning : Form
{
public DateTime startTime1;
public DateTime endTime;
public TimeSpan ts_timeElapsed;
public string s_timeElapsed;
public RoadSign1Meaning()
{
InitializeComponent();
}
public string GetElapsedTimeString()
{
int days = ts_timeElapsed.Days;
int hours = ts_timeElapsed.Hours;
int mins = ts_timeElapsed.Minutes;
int secs = ts_timeElapsed.Seconds;
string x = "";
if (days != 0)
{
x += days.ToString() + ":";
}
if (hours != 0)
{
x += hours.ToString() + ":";
}
if (mins != 0)
{
x += mins.ToString() + ":";
}
if (secs != 0)
{
x += secs.ToString();
}
return x;
}
private void StopButton_Click(object sender, EventArgs e)
{
endTime = DateTime.Now;
ts_timeElapsed = (endTime - startTime1);
s_timeElapsed = GetElapsedTimeString();
ElapsedLabel.Text = "Time Elapsed: " + s_timeElapsed;
Form3 frm = new Form3();
frm.Show();
}
}
}
但是,问题是表格 1 中的时间值未保存,因此表格 2 显示错误的经过时间值。有什么建议可以让我的代码正常工作吗?谢谢!