I am using WPF to make a Windows application. It is a simple GUI which allows a user to choose 1 of 2 RadioButtons
, where one option should launch Notepad once the RadioButton
is selected and a "Submit" button is clicked. I am using a WindowsFormsHost
as a child of the main application and the desired .exe file should launch in the child of the application, giving the effect that the .exe runs "within the current app". However, when debugging the application on Visual Studio, Notepad opens in a separate window and crashes right away.
I have tried several methods suggested in StackOverflow answers (Simon Mourier's answer from here: Hosting external app in WPF window) and also this Microsoft tutorial: https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-hosting-a-win32-control-in-wpf but I am still not getting the desired result.
Here is some of my C# code :
When debugging, it seems like the problem is the in the line SetParent(_process.MainWindowHandle, _panel.Handle);
public partial class MainWindow : Window
{
private System.Windows.Forms.Panel _panel;
private Process _process;
[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);
[DllImport("user32")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
private const int SWP_NOZORDER = 0x0004;
private const int SWP_NOACTIVATE = 0x0010;
private const int GWL_STYLE = -16;
private const int WS_CAPTION = 0x00C00000;
private const int WS_THICKFRAME = 0x00040000;
public MainWindow()
{
InitializeComponent();
}
private void TrackButton_Click(object sender, RoutedEventArgs e)
{
WindowsFormsHost host = new WindowsFormsHost();
_panel = new System.Windows.Forms.Panel();
host.Child = _panel;
if (PostureButton.IsChecked == true) {
// ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
// _process = Process.Start(psi);
_process = Process.Start(new ProcessStartInfo()
{
FileName = @"C:\Windows\System32\notepad.exe",
UseShellExecute = false
//WorkingDirectory = @"C:\Windows\System32",
//FileName = @"notepad.exe"
});
_process.WaitForInputIdle();
try
{
SetParent(_process.MainWindowHandle, _panel.Handle);
// remove control box
int style = GetWindowLong(_process.MainWindowHandle, GWL_STYLE);
style = style & ~WS_CAPTION & ~WS_THICKFRAME;
SetWindowLong(_process.MainWindowHandle, GWL_STYLE, style);
}
catch (InvalidOperationException ex) {
}
// resize embedded application & refresh
ResizeEmbeddedApp();
}
}
User contributions licensed under CC BY-SA 3.0