且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 WinForms 应用程序中运行独立的应用程序?

更新时间:2021-07-05 15:55:56

我的一个朋友以前做过这个工作!

One Of My Friend Did this Work Sometimes Ago !

你应该这样做:

首先导入系统DLL:

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

    [DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
    private static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

现在声明一个计时器并遵循以下代码:

Now declare a Timer And Follow these Codes :

    private const int GWL_STYLE = (-16);
    private const int WS_VISIBLE = 0x10000000;
    Process p;
 /*Closing Is Timer*/
        private void Closing_Tick(object sender, EventArgs e)
    {


            p.Refresh();
            string a = p.ProcessName;              
                SetParent(p.MainWindowHandle, panel1.Handle);
                SetWindowLong(p.MainWindowHandle, GWL_STYLE, WS_VISIBLE);
              MoveWindow(p.MainWindowHandle, 0, 0, this.Width, this.Height, true);


    }
  void run(string add)
    {
        string addres = add;

        try
        {
            p = Process.Start(addres);
            Thread.Sleep(500); // Allow the process to open it's window
            SetParent(p.MainWindowHandle, panel1.Handle);
            SetWindowLong(p.MainWindowHandle, GWL_STYLE, WS_VISIBLE);
            MoveWindow(p.MainWindowHandle, 0, 0, this.Width, this.Height, true);


        }
        catch
        {
            Closeing.Enabled = false;
            MessageBox.Show(addres + "\n" + "Not Found", "Error",
          MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading);
            Environment.Exit(0);

        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Closeing.Enabled = true;
        run(@textBox1.Text); 
    }

Run Method的输入参数是你的应用程序中要运行的程序的路径

Input Parameter Of Run Method Is the path of program that use want to run in your Application

希望这有帮助!:)