MoShe
MoShe

Reputation: 6427

How to open process within Windows form

I would like to open process in within my windows form application.

For example I would like when a user press on button in one of the windows form container the mstsc.exe will open.

And if he will press on the button it will open IE on another container,

[DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
       private void button1_Click(object sender, EventArgs e)
    {
        Process p = Process.Start("mstsc.exe", @"c:\VPN4.rdp");
        Thread.Sleep(3000);
        p.StartInfo.CreateNoWindow = true;    // new
        SetParent(p.MainWindowHandle, this.panel1.Handle);
        p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;   //new

    }

It open the process but not in the windows form ,,,

Upvotes: 3

Views: 13431

Answers (2)

Phil Martin
Phil Martin

Reputation: 466

You can start another process, and place it's window inside your own.

Try using your forms handle instead of the panels. Here is a short example

private void toolStripButton1_Click(object sender, EventArgs e)
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.FileName = "notepad";
  info.UseShellExecute = true;
  var process = Process.Start(info);

  Thread.Sleep(2000);

  SetParent(process.MainWindowHandle, this.Handle);
}

As for the original questions specific problem, I would guess it is due to remote desktop opening other windows for the application to do it's work, and the MainWindowHandle is not the one you are after.

Try using FindWindowEx in the windows API to search for the correct window. If you search by process ID and title, you ought to find the right one. Stackoverflow and google have a large amount of information. Just search for "C# FindWindowEx"

Upvotes: 6

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20745

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "notepad";
info.UseShellExecute = true;
Process.Start(info);

Upvotes: 1

Related Questions