ispiro
ispiro

Reputation: 27683

How do I start a process from my program and have it controlled by visual studio?

In order to start another instance of my program I did something like:

private void button1_Click(object sender, EventArgs e)
{
    Process p = new Process();
    p.StartInfo.FileName = Application.ExecutablePath;
    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
    p.Start();
}

And found that stopping the debugger didn't stop the new window, only the first (-launching) window.

How do I programmatically get the new process to be "under" VS?

Upvotes: 1

Views: 215

Answers (5)

user7116
user7116

Reputation: 64078

Since you're starting your own program a second time, you know it is a GUI. You can keep the Process reference around and call CloseMainWindow (or Kill) on each of them in your FormClosing event handler:

private List<Process> children = new List<Process>();

private void button1_Click(object sender, EventArgs e)
{
    Process p = new Process();
    p.StartInfo.FileName = Application.ExecutablePath;
    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
    p.Start();

    children.Add(p);
}

private Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    foreach (Process p in this.children)
    {
        // posts WM_CLOSE to the main handle of the process
        // which allows a graceful exit, as if the user clicked [X]
        p.CloseMainWindow();
        // p.Kill(); // less graceful, just kill
    }
}

Upvotes: 1

Djoul6
Djoul6

Reputation: 309

You can Change the Start Action for Application Debugging

  1. Right click on your project
  2. Properties
  3. Debug
  4. Start external program

And set the program you want to launch.

If you want to attach to an another instance programmatically, a duplicate question can be found here:

Wich refer this article:

Upvotes: 2

tbddeveloper
tbddeveloper

Reputation: 2447

That Process that you get back has a handle to the running process. You could keep a hold of that in a member variable, rather than a local variable, and on form closing, kill the process.

http://msdn.microsoft.com/en-us/library/e8zac0ca.aspx

Upvotes: 2

syneptody
syneptody

Reputation: 1280

If by "under VS" you mean having Visual Studio be able to debug the external process you may want to consider the "Attach to Process" strategy.

http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx

Upvotes: 0

Eugene
Eugene

Reputation: 1535

Debug -> Attach to Process and select your process from the list.

Upvotes: 0

Related Questions