WPF中,定時系統重啓功能的實現

一、背景

功能需求:定時重啓WPF應用,類似於windows的定時重啓功能。

二、核心知識點

相關的知識點主要有3個:
1. 定時操作:DispatcherTimer類
2. 系統重啓: System.Windows.Forms.Application.Restart();
3. 關閉已啓動的應用:Process.CloseMainWindow();

三、代碼示例

public partial class App : Application
{

    Process currentProcess;//當前進程
    DispatcherTimer timer = new DispatcherTimer();//定義全局的定時器

    public App()
    {
        currentProcess = Process.GetCurrentProcess();
        timer.Interval = new TimeSpan(0, 0, 5);//測試每5秒執行一次
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    /// <summary>
    /// 定時操作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Timer_Tick(object sender, EventArgs e)
    {
        System.Windows.Forms.Application.Restart();
        Application.Current.Shutdown();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        KillExeExceptSelf(currentProcess.ProcessName,currentProcess.Id);
    }

    protected override void OnExit(ExitEventArgs e)
    {
        timer.Stop();
        timer = null;
    }

    /// <summary>
    /// 關閉除了自身以外的所有同名進程
    /// </summary>
    /// <param name="exePath"></param>
    /// <param name="exceptId"></param>
    public  void KillExeExceptSelf(string exePath ,int exceptId )
    {
        try
        {
            foreach (var item in Process.GetProcessesByName(exePath).Where(p=>p.Id != exceptId))
            {
                item.CloseMainWindow();
            }
        }
        catch (Exception ex)
        {

        }
    }

}

說明:
1. System.Windows.Forms.Application.Restart();只是重新啓動了一個應用程序,並沒有關閉已打開的應用,所有還需要使用Application.Current.Shutdown();
2. 每個進程擁有唯一的ID,所以可以通過Process.GetCurrentProcess()獲取當前線程,利用Process.GetProcessesByName(exePath).Where(p=>p.Id != exceptId)查找到所有的同名線程並過濾自身,然後使用CloseMainWindow()關閉線程。

四、代碼下載

https://github.com/saylorMan/RestartApp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章