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

Time:01-20

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 ?

CodePudding user response:

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 (e.g. 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 screenshot

public partial class MainForm : Form
{
    public MainForm() => InitializeComponent();
    protected override void onl oad(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 };
}

CodePudding user response:

You can use this, it will work on runtime :

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