1. 程式人生 > >C#實現WinForm隨WINDOWS服務一起啟動(轉載)

C#實現WinForm隨WINDOWS服務一起啟動(轉載)


/// <summary>/// 啟動所有要啟動的程式
        
/// </summary>        private void StartProgram()
        {
            try
            {
                foreach (string ProgramPath in rwCnfg.GsProgramPaths)
                {
                    string fileName = "";
                    //fileName = System.IO.Path.GetFileName(ProgramPath); 
//檔名
                    
//string ext = System.IO.Path.GetExtension(ProgramPath); //副檔名                    fileName = System.IO.Path.GetFileNameWithoutExtension(ProgramPath);// fileName.Replace(ext, "");                    if (!IsExistProcess(fileName))
                    {
                        ProcessStartInfo startInfo = new
 ProcessStartInfo(ProgramPath);
                        startInfo.WindowStyle = ProcessWindowStyle.Normal;
                        Process.Start(startInfo);

                        Common.wLog("完成啟動程式: " + fileName + ",完整路徑:" + ProgramPath + " . " + System.DateTime.Now.ToString());

                        System.Threading.Thread.Sleep(3
 * 1000); //間隔3秒;                    }
                }
            }
            catch (Exception err)
            {
                Common.wLog(err.ToString());
            }

        }

        /// <summary>/// 檢查該程序是否已啟動
        
/// </summary>/// <param name="processName"></param>/// <returns></returns>        private bool IsExistProcess(string processName)
        {

            Process[] MyProcesses = Process.GetProcesses();
            foreach (Process MyProcess in MyProcesses)
            {
                if (MyProcess.ProcessName.CompareTo(processName) == 0)
                {
                    return true;

                }
            }
            return false;
        }