使用System.Diagnostics.Process启动第三方应用程序

时间:2012-05-31 10:07:06

标签: c# process singleton

所有,我正在开发一个需要在运行时启动另一个应用程序的应用程序。要启动我使用System.Diagnostics.Process的第三方应用程序,并确保我从未启动过第二方应用程序两次,我会使用单例模式。

单身人士正在工作,但Process.Start()方法不是。这是因为我从单例中返回了相同的Process对象,Start()正在启动第三方应用程序的另一个实例。

来自MSDN - Process.Start() page

"Starts (or reuses) the process resource that is specified by the StartInfo property 
of this Process component and associates it with the component."

建议它应该重用Process的实例。我错过了什么?

感谢您的时间。

3 个答案:

答案 0 :(得分:1)

也许您应该考虑使用Process.GetProcessesByName来了解您启动的应用程序是否已在运行。

答案 1 :(得分:1)

这是我用来启动第三方应用程序的功能:

    public static void ProcessStart(string ExecutablePath, string sArgs, bool bWait)
    {
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents = false;
        proc.StartInfo.FileName = ExecutablePath;

        if(sArgs.Length > 0)
            proc.StartInfo.Arguments = sArgs;


        proc.Start();

        if(bWait)
            proc.WaitForExit();

        if(ProcessLive(ExecutablePath))
            return true;
        else
            return false;               

    }

ExecutablePath:可执行文件的完整路径

sArgs:命令行参数

bWait:等待进程退出

在我的情况下,我使用辅助函数来确定进程是否已在运行。这不是您正在寻找的,但它仍然有效:

    public static bool ProcessLive(string ExecutablePath)
    {
        try
        {

            string strTargetProcessName = System.IO.Path.GetFileNameWithoutExtension(ExecutablePath);

            System.Diagnostics.Process[] Processes = System.Diagnostics.Process.GetProcessesByName(strTargetProcessName);

            foreach(System.Diagnostics.Process p in Processes)
            {
                foreach(System.Diagnostics.ProcessModule m in p.Modules)
                {
                    if(ExecutablePath.ToLower() == m.FileName.ToLower())
                        return true;
                }
            }
        }
        catch(Exception){}

        return false;

    }

答案 2 :(得分:0)

按如下方式使用

Process[] chromes = Process.GetProcessesByName("ProcessName"); to check whether ur process is already running or not. Based on the u can use the process already running.