博客园

进程调用等待及进程退出监控源码

 public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 开启一个程序并等待程序关闭
        /// </summary>
        /// <param name="appPath">程序绝对路径</param>
        /// <param name="args">参数</param>
        public void RunAppAndWait(string appPath, string args)
        {

            System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();

            //设置外部程序名  
            Info.FileName = appPath;

            Info.Arguments = args;
            //声明一个程序类  
            System.Diagnostics.Process Proc;

            try
            {
                this.Hide();
                Proc = System.Diagnostics.Process.Start(Info);
                Proc.WaitForExit();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                this.Show();
                return;
            }
            this.Show();
        }


        private void btnRunProcess_Click(object sender, EventArgs e)
        {
            RunAppAndWait(txtApp.Text, txtArgs.Text);
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            txtApp.Text = Application.StartupPath + "\\app.exe";
            txtArgs.Text = " abc";

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(txtProcess.Text);
            if (procs.Length > 0)
            {
                foreach (System.Diagnostics.Process item in procs)
                {
                    item.EnableRaisingEvents = true;
                    item.Exited += new EventHandler(item_Exited);
                }
            }

        }
        public delegate void MyInvoke(string str);

        private void SetText(string s)
        {
            if (txtStatus.InvokeRequired)
            {
                MyInvoke _myInvoke = new MyInvoke(SetText);
                this.Invoke(_myInvoke, new object[] { s });
            }
            else
            {
                this.txtStatus.AppendText(s);
            }
        }

        void item_Exited(object sender, EventArgs e)
        {

            var p = sender as System.Diagnostics.Process;
            SetText(p.ProcessName + "已经退出");
        }

    }

  

posted @ 2013-01-29 09:28  一心一意  阅读(618)  评论(0编辑  收藏  举报

Powered by:
一心一意
Copyright & JGuang