run a foreign exe inside a windows form app

后端 未结 2 1659
猫巷女王i
猫巷女王i 2020-12-18 13:21

i have a c# powered windows form app and i want to run a exe inside it. that program is another seperate executable file. lets say that that exe is not a dot net app, but wr

相关标签:
2条回答
  • 2020-12-18 14:02
        [DllImport("user32.dll")]
            static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);    
    
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
    
                    Process p = Process.Start(textBox1.Text);
                    p.WaitForInputIdle();
                    SetParent(p.MainWindowHandle, panel1.Handle);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    }
    

    Reference to fardjad but it can only run small programs like notepad, firefox, safari

    0 讨论(0)
  • 2020-12-18 14:07

    You can do this by PInvoking SetParent():

    [DllImport("user32.dll")]
            static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
    

    First you need to start the third party application within your application:

    var clientApplication = Process.Start("PATH_TO_YOUR_EXECUTABLE");
    

    then set its MainWindowHandle to your main window handle:

    SetParent(clientApplication.MainWindowHandle, YourMainWindowOrAContainerControl.Handle);
    
    0 讨论(0)
提交回复
热议问题