在我的WPF程序中,有一个带有此代码后缀的按钮:
**Outside the Click event:**
bool started = false;
**In the Click Event:**
if (started == false)
{
started = true;
btnStart.Content = "Stop";
//---------Clock Code-------------
stopwatch.Start();
}
else
{
started = false;
btnStart.Content = "Start";
//---------Clock Code------------
stopwatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopwatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
tbDuration.Text = elapsedTime;
}
但是,如果我启动程序并按下按钮,它将始终显示0。 我无法调试它,因为Visual Studio崩溃了...
我该怎么办?
还是您有更好的方法来做到这一点? 我只想测量两次按下之间的时间并将其输出到文本框。
我还希望在文本框中实时监视时间。
谢谢
答案 0 :(得分:1)
假设您的代码看起来像这样,就可以正常工作:
public Stopwatch stopwatch = new Stopwatch();
bool started = false;
private void button1_Click(object sender, EventArgs e)
{
if (started == false)
{
started = true;
button1.Text = "Stop";
//---------Clock Code-------------
stopwatch.Start();
}
else
{
started = false;
button1.Text = "Start";
//---------Clock Code------------
stopwatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopwatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
MessageBox.Show(elapsedTime);
}
}
答案 1 :(得分:0)
解决方案:(来自@TheGeneral) 将秒表放入实例成员:
private Stopwatch stopwatch = new Stopwatch();