goblin01
goblin01

Reputation: 101

How can I prevent C# WPF application starting other app twice?

I have a problem in making a C# app; i use proc.Start(); as starting an other app. The problem is that this method runs specified app twice. I looked a lot into Web and I didn't find a good answer. The code snippet:

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();
}

When it's executed, in Task Manager i see 2 processes of specified instances using proc.Start() in the app. How can I fix that?

Upvotes: 0

Views: 558

Answers (1)

TheSoftwareJedi
TheSoftwareJedi

Reputation: 35196

As was stated in the comment reply, you're starting it once in the assignment of the using statement, then again a few lines down.

You want to use the default constructor, then set what you need, then start it. See this example here (also pasted below):

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);
            }
        }
    }
}

Upvotes: 2

Related Questions