My question is how to run an application(.exe) inside WPF application. I mean running inside a window of an application, not an external running an application.
Thanks in advance :D
WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).
Yes you can, both Windows Forms within a WPF application, and WPF controls within Windows Forms.
What you are looking to do is entirely possible, but it does come with a few bugs, so don't expect an easy ride. What you need to do is create a class that inherits from HwndHost
and overrides the BuildWindowCore()
method. See the example from Microsoft at http://msdn.microsoft.com/en-us/library/ms752055.aspx
In the above example, they give you the notion of being able to put a Win32 control within your WPF form, but you can use the same architecture to load the MainWindowhandle
of your created Notepad process into the child of the border. Like this:
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;
}
Please keep in mind that you will need to import a few functions from the User32.dll to be able to set the style of the window and set the parent window handle:
[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);
Also make sure that you are including:
using System.Windows.Interop;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
This is my first answer on a forum so please let me know if it needs some work. Also reference Hosting external app in WPF window but don't worry about DwayneNeed stuff. Just use SetParent() as you see in my code above. Just be careful if you try embedding the app inside a tab page. You will encounter some fun there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With