[英]How can I display as text the properties of an element in a textbox in windows form application c#?
[英]How can I display the current date and time in my C# windows form application's text property?
我想在我的 C# windows 表格申請的標題中實時顯示當前日期和時間。
我的資源說我需要使用 datetime.now.tostring(); 這樣做,但我不知道怎么做。 有任何想法嗎?
您希望使用窗體的Text
屬性在窗體的標題欄中顯示當前日期和時間。 持續更新時間的最簡單方法是使用System.Windows.Forms.Timer
,它會在 UI 線程上發出計時。
使用其他計時器(例如System.Timers.Timer
)或從后台工作者更新 UI 控件通常可能很棘手。 如果您的 WinForms 應用程序可能最終被移植到 iOS 或 Android 設備,則有更好、更便攜的替代方案。 處理由后台任務生成的事件的一個好做法是使用BeginInvoke來確保控件在 UI 線程上更新。
然而,在這種簡單的情況下,只需處理Tick
事件:
Text
屬性。最小的例子
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 };
}
您可以使用它,它將在運行時運行:
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
this.Text = "Your title here";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.