How can I run another application within a panel of my C# program? How can I run another application within a panel of my C# program? windows windows

How can I run another application within a panel of my C# program?


Using the win32 API it is possible to "eat" another application. Basically you get the top window for that application and set it's parent to be the handle of the panel you want to place it in. If you don't want the MDI style effect you also have to adjust the window style to make it maximised and remove the title bar.

Here is some simple sample code where I have a form with a button and a panel:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Diagnostics;using System.Runtime.InteropServices;using System.Threading;namespace WindowsFormsApplication2{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            Process p = Process.Start("notepad.exe");            Thread.Sleep(500); // Allow the process to open it's window            SetParent(p.MainWindowHandle, panel1.Handle);        }        [DllImport("user32.dll")]        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);    }}

I just saw another example where they called WaitForInputIdle instead of sleeping. So the code would be like this:

Process p = Process.Start("notepad.exe");p.WaitForInputIdle();SetParent(p.MainWindowHandle, panel1.Handle);

The Code Project has a good article one the whole process: Hosting EXE Applications in a WinForm project


I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).

Here's a link to OLE info to get started:

http://en.wikipedia.org/wiki/Object_Linking_and_Embedding


Another interesting solution to luch an exeternal application with a WinForm container is the follow:

[DllImport("user32.dll")]static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);private void Form1_Load(object sender, EventArgs e){    ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");    psi.WindowStyle = ProcessWindowStyle.Minimized;    Process p = Process.Start(psi);    Thread.Sleep(500);    SetParent(p.MainWindowHandle, panel1.Handle);    CenterToScreen();    psi.WindowStyle = ProcessWindowStyle.Normal;}

The step to ProcessWindowStyle.Minimized from ProcessWindowStyle.Normal remove the annoying delay.

enter image description here