Search code examples
c#mdi

Why can't I open an external application as MDI?


When I open an external application as MDI Child, the application opens, but not as an MDI child. I have a class that runs notepad.exe correctly, but it doesn't work with my own application:

public class ExternalApp {
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    private static extern uint SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
    public static void LoadProcessInControl(string app_path, Control parent) {
        System.Diagnostics.Process p = System.Diagnostics.Process.Start(app_path);
        p.WaitForInputIdle();
        ExternalApp.SetParent(p.MainWindowHandle, parent.Handle);
    }
}

I call the function with this:

ExternalApp.LoadProcessInControl(@"C:\Users\Bálint\Documents\Visual Studio 2013\Projects\TesztApp\TesztApp.exe", this);

What's the problem?


Solution

  • Actually I was mistaken in my comment those properties don't need to be set. It's been awhile. :) To do this I've had some success using a panel inside a child form:

    public partial class Form2 : Form
    {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, Int32 wParam, Int32 lParam);
        public Form2()
        {
            InitializeComponent();
            Process process = new Process();
            process.StartInfo.FileName = "Notepad.exe";
            process.Start();
            process.WaitForInputIdle();
            SetParent(process.MainWindowHandle, panel1.Handle);
            //This maximizes the process window. 
            SendMessage(process.MainWindowHandle, 274, 61488, 0);
            return;
        }
    }
    

    The documentation for SendMessage is here. The child form is shown like this, with Notepad embedded:

    public Form1()
    {
        InitializeComponent();
        Form2 newForm2 = new Form2();
        newForm2.MdiParent = this;
        newForm2.Show();
    }