WPF中,定时系统重启功能的实现

6 篇文章 0 订阅

一、背景

功能需求:定时重启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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值