在 C# 中实时显示当前时间可以使用 Windows 窗体应用程序或 WPF 应用程序来创建界面。以下是一个使用 Windows 窗体的示例:
-
打开 Visual Studio 并创建一个新的 Windows 窗体应用程序项目。
-
在窗体上添加一个 Label 控件,这将用于显示当前时间。
-
在窗体的代码文件中添加以下代码:
csharp
using System;
using System.Windows.Forms;
namespace RealTimeClock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 使用一个定时器来实时更新时间
Timer timer = new Timer();
timer.Interval = 1000; // 每秒更新一次
timer.Tick += new EventHandler(UpdateClock);
timer.Start();
}
private void UpdateClock(object sender, EventArgs e)
{
// 获取当前时间并在 Label 控件上显示
DateTime currentTime = DateTime.Now;
label1.Text = currentTime.ToString("HH:mm:ss");
}
}
}
- 在窗体设计器中,双击窗体以创建 Load 事件处理程序,并在其中启动定时器:
csharp
private void Form1_Load(object sender, EventArgs e)
{
UpdateClock(null, null); // 手动调用一次以初始化时间
}
-
在窗体设计器中,将 Label 控件的文本属性设置为初始时间(可选)。
-
生成并运行你的应用程序。
现在,你的 Windows 窗体应用程序将每秒更新一次显示当前时间。你可以根据需要自定义时间格式以满足你的要求。如果你使用 WPF 应用程序,也可以使用类似的方法实现。