07-控制檯程序實現關閉進程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace KillProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("請輸入進程名:");
            string processName = Console.ReadLine();
            int killValue = 0;
            killValue = KillProc(processName);
            //CloseProcess.KillProc(processName, ref killValue);
            switch (killValue)
            {
                case 0:
                    Console.WriteLine("進程 {0} 關閉成功", processName);
                    break;
                case 1:
                    Console.WriteLine("當前沒有正在運行的進程!");
                    break;
                case 2:
                    Console.WriteLine("結束進程 {0} 出錯!", processName);
                    break;
                default:
                    break;
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 關閉指定進程的方法
        /// </summary>
        /// <param name="processName">進程名</param>
        /// <returns></returns>
        private static int KillProc(string processName)
        {
            int killValue = 0;
            try
            {
                Process[] ps = Process.GetProcesses();
                if (ps == null)
                {
                    killValue = 1;
                    return killValue;
                }
                foreach (Process item in ps)
                {
                    if (item.ProcessName.ToLower()==processName.ToLower())
                    {
                        item.Kill();
                    }
                }
            }
            catch //出現異常,代表 kill 進程失敗
            {
                killValue = 2;
            }

            return killValue;
        }
    }
}
相關文章
相關標籤/搜索