I found timer code from a web site and used it in my application and it works fine if I use the timer code inside a button_click handler, but I need to use the timer when I call a method, so I did copy and paste the same code from the button_click into the method but the timer always gives me zero. How do I fix it?
The following is the timer code.
public partial class Form1 : Form
{
//Timer decleration
DateTime startTime, StopTime;
TimeSpan stoppedTime;
bool reset;
bool startVariabl = true;
// The rest of the code..
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (startVariable) startMethod();
//
//The rest of the code...
}
privat开发者_如何学Pythone void startMethod()
{
//Timer
tmDisplay.Enabled = true;
// Reset display to zero
reset = true;
lblElapsed.Text = "00:00.00.0";
// Start timer and get starting time
if (reset)
{
reset = false;
startTime = DateTime.Now;
stoppedTime = new TimeSpan(0);
}
else
{
stoppedTime += DateTime.Now - StopTime;
}
}
private void tmDisplay_Tick(object sender, EventArgs e)
{
DateTime currentTime;
//Determine Ellapsed Time
currentTime = DateTime.Now;
// Display Time
lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
}
private string HMS(TimeSpan tms)
{
//Format time as string; leaving off last six decimal places.
string s = tms.ToString();
return (s.Substring(0, s.Length - 6));
}
I am new C# learner.
as keyboardP suggested in a comment you should add this line:
tmDisplay.Tick += new EventHandler(tmDisplay_Tick);
usually Tick handler is set once (unless you need to switch it to other callback or nullify it for some reason) so I would add it in your Form constructor assuming that timer is already created then or after timer initialization if you do it in some method.
精彩评论