How can I run clock while form is open?

I am using this code:

DateTime present = DateTime.Now;

label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString();

I want a running clock when I open the form and should be able to click other objects while the clock is running.

有帮助吗?

解决方案

You need to create System.Threading.Timer object and on it's Tick event update your label text. Also it's more correct to do

    DateTime.Now.ToString("hhMMss");

or

    DateTime.Now.ToShortTimeString();

instead several .ToString() calls.

The result code will be something like that

    new System.Threading.Timer((state) => { BeginInvoke((Action)delegate() { label1.Text = DateTime.Now.ToShortTimeString(); }); }, null, 1000, 1000);

其他提示

You can try with the class DispatcherTimer

    DispatcherTimer dpTimer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();
        dpTimer.Tick += new EventHandler(dpTick);
        dpTimer.Interval = new TimeSpan(0, 0, 1);
        dpTimer.Start();
    }

    private void dpTick(object sender, EventArgs e)
    {
        DateTime present = DateTime.Now;
        timer_label.Content = present.Hour.ToString() + present.Minute.ToString() + present.Second.ToString();
    }

If you want to use the Timer, check this solution:

        new System.Threading.Timer((state) => 
        {
            Action action = () => timer_label.Content = DateTime.Now.ToString("hh:MM:ss");
            Dispatcher.BeginInvoke(action);
        }, null, 1000, 1000);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top