WPF定时器的用法(1)

时间:2022-03-04 23:24:55

大家好,本人第一次写帖子,如有错误,请及时指出!

界面:

WPF定时器的用法(1)

 

xaml:

<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
    <Button Name="btn_1" Content="惦记我?" Click="btn_1_Click"></Button>
</StackPanel>

 

WPF逻辑代码:

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.Timers;

namespace demo2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

System.Timers.Timer t = new System.Timers.Timer(3000);
//实例化Timer类,设置时间间隔为3秒
private void btn_1_Click(object sender, RoutedEventArgs e)
{

t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
//到达时间的时候就执行事件
t.AutoReset = true;
//设置时候执行一次(false)还是一直执行(true)
t.Enabled = false;
//需要调用timer.start()或者timer.Enabled=true来启动它,timer.Start()的内部原理还是设置timer.Enabled=true;

}

public void theout(object source,System.Timers.ElapsedEventArgs e) {

MessageBox.Show("惦记你大爷!!!");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{

}


}
}