[英]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.我想在我的 C# windows 表格申请的标题中实时显示当前日期和时间。
My resource says that I need to use datetime.now.tostring();我的资源说我需要使用 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.您希望使用窗体的Text
属性在窗体的标题栏中显示当前日期和时间。 The simplest way to update the time continuously is to use System.Windows.Forms.Timer
which issues its ticks on the UI thread.持续更新时间的最简单方法是使用System.Windows.Forms.Timer
,它会在 UI 线程上发出计时。
Using other timers (eg System.Timers.Timer
) or updating UI controls from background workers generally can be tricky.使用其他计时器(例如System.Timers.Timer
)或从后台工作者更新 UI 控件通常可能很棘手。 If your WinForms app might end up being ported to an iOS or Android device, there are better more-portable alternatives.如果您的 WinForms 应用程序可能最终被移植到 iOS 或 Android 设备,则有更好、更便携的替代方案。 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.处理由后台任务生成的事件的一个好做法是使用BeginInvoke来确保控件在 UI 线程上更新。
In this straightforward case however, simply handle the Tick
event:然而,在这种简单的情况下,只需处理Tick
事件:
Text
property using DateTime standard format strings .使用DateTime 标准格式字符串格式化Text
属性。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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.