WPF 程序中啟動和關閉外部.exe程序


 當需要在WPF程序啟動時,啟動另一外部程序(.exe程序)時,可以按照下面的例子來:

C#后台代碼如下:

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;

namespace WpfApplication2
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            System.Diagnostics.Process.Start(@"C:\Program Files\Microsoft Office\Office14\EXCEL.EXE");    //調用該命令,在程序啟動時打開Excel程序
        }
    }
}

C#后台代碼:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication2
{
    /// <summary>
    /// App.xaml 的交互邏輯
    /// </summary>
    public partial class App : Application
    {
        protected override void OnExit(ExitEventArgs e)     //該重寫函數實現在程序退出時關閉某個進程
        {
            Process []myProgress;
            myProgress=Process.GetProcesses();          //獲取當前啟動的所有進程
            foreach(Process p in myProgress)            //關閉當前啟動的Excel進程
            {
                if (p.ProcessName == "EXCEL")          //通過進程名來尋找
                {
                    p.Kill();
                    return;
                }                  
            }
            base.OnExit(e);
        }
    }
}

說明:在WPF程序中,Application類的作用有:

    (1)可以跟蹤應用程序的生存周期;

    (2)共享應用程序范圍的屬性和資源;

    (3)管理獨立應用程序中的窗口;

補充:對於Application類,可以有很多屬性、事件和方法供調用。當需要實現自定義功能時,可以override方法(標記為Virtual的方法)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM