我正在使用WPF制作Windows应用程序。这是一个简单的GUI,它允许用户选择2 RadioButtons
中的1个,一旦选择RadioButton
并单击“提交”按钮,一个选项应启动记事本。我正在使用WindowsFormsHost
作为主应用程序的子级,并且所需的.exe文件应在该应用程序的子级中启动,从而使.exe在“当前应用程序内”运行。但是,在Visual Studio上调试应用程序时,“记事本”会在单独的窗口中打开,并立即崩溃。
我尝试了StackOverflow答案(Simon Mourier的答案:Hosting external app in WPF window)中建议的几种方法,以及本Microsoft教程:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-hosting-a-win32-control-in-wpf,但仍然没有得到想要的结果。
这是我的一些C#代码:
调试时,问题似乎出在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();
}
}