System.Windows.Forms.Timer, System.Threading.Timer, System.Timer,三种Timer使用如下
第一种:System.Windows.Forms.Timer使用
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowText(IntPtr hWnd, string text);
[DllImport("User32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
/// <summary>
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
const int WM_CLOSE = 0x10;
const int BM_CLICK = 0xF5;
int FunCord;
IntPtr hwnd;
int t;
System.Windows.Forms.Timer timer;
private void StartTimer(int interval)
{
Timer timer = new Timer();
timer.Interval = interval;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;
}
private void timer_Tick(object sender, EventArgs e)
{
hwnd = FindWindow(null, t.ToString() + "秒后关闭");
t = t - 1;
SetWindowText(hwnd, t.ToString() + "秒后关闭");
if (t == 0)
{
timer.Enabled = false;
}
}
第二种:System.Threading.Timer使用
System.Threading.Timer threadTimer = new System.Threading.Timer(new TimerCallback(TimerUp), null, Timeout.Infinite, 1000);
//立即开始计时,时间间隔1000毫秒
threadTimer.Change(0, 1000);
/// <summary>
/// 定时到点执行的事件
/// </summary>
/// <param name="value"></param>
private void TimerUp(object value)
{
try
{
timeOutValidate -= 1;
}
catch (Exception ex)
{
Program.Log.Error("执行定时到点事件失败:" + ex.Message);
}
}
第三种:System.Timer使用
System.Timers.Timer timer = new System.Timers.Timer(interval);
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerTimeOut);
timer.Enabled = true;
timer.Start();
.
/// <summary>
/// Timer类执行定时到点事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimerTimeOut(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timeOut -= 1;
}
catch (Exception ex)
{
Program.Log.Error("执行定时到点事件失败:" + ex.Message);
}
}