假设我有两种形式.第一个包含开始按钮,另一个是停止按钮.有没有办法可以确定按下开始和停止按钮之间经过的时间,并以第二种形式显示.
我尝试这样做并得出这些代码
表格1:开始按钮
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
表格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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然而,问题是表格1的时间值不保存,因此表格2显示错误的经过时间值.有什么建议让我的代码有效吗?谢谢!
将开始时间传递给第二种形式
private void StartButton_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(DateTime.Now);
frm.Show();
this.Hide();
}
Run Code Online (Sandbox Code Playgroud)
然后使用它
public partial class Form2 : Form
{
private DateTime startTime;
public Form2(DateTime startTime)
{
InitializeComponent();
this.startTime = startTime;
}
private void StopButton_Click(object sender, EventArgs e)
{
endTime = DateTime.Now;
ts_timeElapsed = (endTime - startTime);
s_timeElapsed = GetElapsedTimeString();
ElapsedLabel.Text = "Time Elapsed: " + s_timeElapsed;
Form3 frm = new Form3();
frm.Show();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3969 次 |
| 最近记录: |