如何在wpf应用程序中运行应用程序?

时间:2011-06-25 12:56:41

标签: wpf

我的问题是如何在WPF应用程序中运行应用程序(.exe)。 我的意思是在应用程序的窗口内运行,而不是在外部运行应用程序。

提前致谢:D

1 个答案:

答案 0 :(得分:18)

你要做的事情是完全可能的,但它确实带来了一些错误,所以不要指望轻松骑行。您需要做的是创建一个继承自HwndHost的类并覆盖BuildWindowCore()方法。请参阅Microsoft的示例http://msdn.microsoft.com/en-us/library/ms752055.aspx

在上面的示例中,它们为您提供了能够将Win32控件放在WPF窗体中的概念,但是您可以使用相同的体系结构将创建的记事本进程的MainWindowhandle加载到子窗口中。边界。像这样:

protected override HandleRef BuildWindowCore(HandleRef hwndParent)
    {
        ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
        psi.WindowStyle = ProcessWindowStyle.Minimized;
        _process = Process.Start(psi);
        _process.WaitForInputIdle();

        // The main window handle may be unavailable for a while, just wait for it
        while (_process.MainWindowHandle == IntPtr.Zero)
        {
            Thread.Yield();
        }

        IntPtr notepadHandle = _process.MainWindowHandle;

        int style = GetWindowLong(notepadHandle, GWL_STYLE);
        style = style & ~((int)WS_CAPTION) & ~((int)WS_THICKFRAME); // Removes Caption bar and the sizing border
        style |= ((int)WS_CHILD); // Must be a child window to be hosted

        SetWindowLong(notepadHandle, GWL_STYLE, style);
        SetParent(notepadHandle, hwndParent.Handle);

        this.InvalidateVisual();

        HandleRef hwnd = new HandleRef(this, notepadHandle);
        return hwnd;
    }

请记住,您需要从User32.dll导入一些函数才能设置窗口样式并设置父窗口句柄:

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

[DllImport("user32")]
private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

还要确保包括:

using System.Windows.Interop;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

这是我在论坛上的第一个答案,如果需要一些工作,请告诉我。另请参考Hosting external app in WPF window但不要担心DwayneNeed的内容。只需使用上面代码中的SetParent()。如果您尝试在应用页面中嵌入应用,请务必小心。你会在那里遇到一些乐趣。