猿问

如何防止 C# WPF 应用程序启动其他应用程序两次?

我在制作 C# 应用程序时遇到问题;我proc.Start();用作启动其他应用程序。问题是此方法运行指定的应用程序两次。我在网上看了很多,我没有找到一个好的答案。代码片段:


using (Process proc = Process.Start(BotProcess))

{

    StatusLabel.Content = "Starting...";

    proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);

    proc.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);

    proc.Start();

    StatusLabel.Content = "Running";

    proc.BeginOutputReadLine();

}

执行时,在任务管理器中,我看到proc.Start()应用程序中使用的指定实例的 2 个进程。我该如何解决?


侃侃无极
浏览 205回答 1
1回答

不负相思意

正如评论回复中所述,您在 using 语句的赋值中启动它一次,然后再向下几行。您想使用默认构造函数,然后设置您需要的内容,然后启动它。在此处查看此示例(也粘贴在下面):using System;using System.Diagnostics;using System.ComponentModel;namespace MyProcessSample{    class MyProcess    {        public static void Main()        {            Process myProcess = new Process();            try            {                myProcess.StartInfo.UseShellExecute = false;                // You can start any process, HelloWorld is a do-nothing example.                myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";                myProcess.StartInfo.CreateNoWindow = true;                myProcess.Start();                // This code assumes the process you are starting will terminate itself.                 // Given that is is started without a window so you cannot terminate it                 // on the desktop, it must terminate itself or you can do it programmatically                // from this application using the Kill method.            }            catch (Exception e)            {                Console.WriteLine(e.Message);            }        }    }}
随时随地看视频慕课网APP
我要回答