Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,838 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Extract
{
public partial class TimeCounter : Label
{
private Timer _timer;
private int _elapsedSeconds;
public TimeCounter()
{
InitializeComponent();
_timer = new Timer
{
Interval = 1000,
Enabled = true
};
_timer.Tick += (sender, args) =>
{
_elapsedSeconds++;
TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
this.Text = time.ToString(@"hh\:mm\:ss");
};
}
private void TimeCounter_Load(object sender, EventArgs e)
{
}
}
}
I tried to change the line _elapsedSeconds++; to _elapsedSeconds--; but it's keep counting up. I want to be able to change the counter either to count down or up.
In the following example, the Timer was dropped from the ToolBox.
using System;
using System.Windows.Forms;
namespace TimerUpDown
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool _direction;
private int _seconds;
private int _highValue = 10;
private int _lowValue = 0;
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
_direction = checkBox1.Checked;
_seconds = _direction ? _lowValue : _highValue;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_direction)
{
_seconds++;
}
else
{
_seconds--;
}
label1.Text = TimeSpan.FromSeconds(_seconds).ToString("mm\\:ss");
if (_seconds == _lowValue || _seconds >= _highValue)
{
timer1.Enabled = false;
}
}
}
}