使用Process在winforms中显示外部程序

时间:2014-12-10 01:03:16

标签: c# winforms process

我正在尝试将一部分外部程序(其窗口的一部分)嵌入到我正在开发的现有WinForm中。

以下在线示例,我发布了以下内容。我假设进程名称是唯一的,单数的,并且它已经打开,在示例中:

private void button1_Click(object sender, EventArgs e)
{
    Process[] myProc = Process.GetProcessesByName("the_external_program_i_want");
    Process p = myProc[0];
    IntPtr appWin = p.MainWindowHandle;
    SetParent(appWin, this.Handle);
    SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE);
    MoveWindow(appWin, panel1.Location.X, panel1.Location.Y, panel1.Width, panel1.Height, true);
}

我的问题是,在我关闭WinForm之后,我意识到这个外部程序会触发一个弹出框,说'" program_name已停止工作"。

我的问题是,在WinForm中我是否需要调用其他函数来正确关闭外部程序?

谢谢!

1 个答案:

答案 0 :(得分:1)

首先使p变量可供整个类访问。 然后向FormClosing事件添加一个事件侦听器:

this.FormClosing += Window_FormClosing;

void Window_FormClosing(object sender, FormClosingEventArgs e)
{
    p.Kill();
}