简体   繁体   中英

How can I display the current date and time in my C# windows form application's text property?

I want to show the current date and time in live in the title of my C# windows form Application.

My resource says that I need to use datetime.now.tostring(); to do so, but I don't know how. Any ideas?

You want to display the current date and time in the title bar of your Form using its Text property. The simplest way to update the time continuously is to use System.Windows.Forms.Timer which issues its ticks on the UI thread.

Using other timers (eg System.Timers.Timer ) or updating UI controls from background workers generally can be tricky. If your WinForms app might end up being ported to an iOS or Android device, there are better more-portable alternatives. A good practice for handling events generated by backgound tasks is to use BeginInvoke to ensure that the control is updated on the UI thread.

In this straightforward case however, simply handle the Tick event:


Minimal Example

截屏

public partial class MainForm : Form
{
    public MainForm() => InitializeComponent();
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        _timer.Tick += onTimerTick;
        _timer.Start();
    }

    private void onTimerTick(object? sender, EventArgs e)
    {
        var now = DateTime.Now;
        Text = $"Main Form - {now.ToShortDateString()} {now.ToLongTimeString()}";
    }

    System.Windows.Forms.Timer _timer= new System.Windows.Forms.Timer { Interval= 1000 };
}

You can use this, it will work on runtime:

public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
            this.Text = "Your title here";
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM