ThEpRoGrAmMiNgNoOb
ThEpRoGrAmMiNgNoOb

Reputation: 1294

C# - Display running time in winform textbox

How can I automatically display current time running or increment every second in my textbox when my form loads?

I tried

myTextBox.Text = DateTime.Now.ToString();

but only displays static time.

Upvotes: 0

Views: 2055

Answers (2)

Sievajet
Sievajet

Reputation: 3523

Try this

public partial class FormWithTimer : Form
{
    Timer timer = new Timer();

    public FormWithTimer()
    {
        InitializeComponent();

        timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
        timer.Interval = 1000;              // Timer will tick evert second
        timer.Enabled = true;                       // Enable the timer
        timer.Start();                              // Start the timer
    }

    void timer_Tick(object sender, EventArgs e)
    {
        myTextBox.Text = DateTime.Now - Process.GetCurrentProcess().StartTime;
    }

}

However while debugging this may show the vshost process time.

Upvotes: 1

Danson Mwangi
Danson Mwangi

Reputation: 61

Add a timer,set the interval as 1 and make sure its enabled then on the timer's event put your code

Upvotes: 0

Related Questions