大家在使用C#进行编程时,总会遇到,一些实时显示刷新时间的项目,但是呢许多刚接触C#的小白简直是噩梦,尤其使用WPF时,又没有Timer控件好不容易找到了显示时间代码,发现只能显示一次最新读取的时间,接下来就不多说废话了,代码上手。
1. WPF版本
创建项目后直接粘贴复制即可适用于小白,如果是借鉴直接看下方后端代码即可。切忌如果是粘贴复制的话一定要注意namespace是不是和你创建项目的名称是一样的,如果不一样切换成你创建项目的名称即可。
详细代码如下:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="Timer1" HorizontalAlignment="Left" Height="85" Margin="102,107,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="311" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="18"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
long _start;
public MainWindow()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
_start = Environment.TickCount;
timer.Tick += timer_Tick;
timer.IsEnabled = true;
}
void timer_Tick(object sender, EventArgs e)
{
Timer1.Text = DateTime.Now.ToString("yyyy-dd-MM HH:mm:ss");
}
}
}
效果如下:
2. Windows窗体 窗体程序就比较简单了,创建好项目后先从工具箱拖拽一个TextBox,命名为Timer123,然后从工具箱拖拽一个timer的控件,在右下角的属性栏中进行修改2个属性(Enable设置为True;Interval设置为1000(代表一秒))。
双击你创建的timer,添加命令 this.Timer123.Text = DateTime.Now.ToString();
详细代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Timer123.Text = DateTime.Now.ToString();
}
}
}
效果如下:
3. 控制台应用 也比较简单创建如下项目
别忘了修改名称代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 1000;
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
Console.ReadKey();
}
static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.Write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
Console.Write(DateTime.Now.ToString("yyyy-dd-MM HH:mm:ss"));
}
}
}
效果如下:
以下就是显示时间的三种方式了,比较简单,也希望可以帮助到大家。