I have the below code in a COM interop project(interacts with the parent window) that first creates a WPF dialog in a STA thread. The dialog is displayed properly from the parent window and is supposed to pass-on the XML string to the COM interop project. This is also done successfully and the dialog then closed. I have another workflow when the parent window again needs to create and show this dialog. So the method 'LaunchHostDlg' again gets hit, but when i checked 'hostDlg.Owner' in debug mode, it is null and when the line 'HostDlg.ShowDialog()' gets called, it throws a Win32 exception with the message 'Invalid Window Handle'.
private ManualResetEvent dialogCompletedEvent = new ManualResetEvent(false);
private void LaunchHostDlg(int handle, string ptXML)
{
var staThread = new Thread(() =>
{
// Launch custom dialog from the WPF application's thread
var hostDlg = new HostDlg(handle);
hostDlg.Loaded += (sender, e) =>
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
// Asynchronously initialize WebView2 when the custom dialog is ready
hostDlg.CreateDialogContent(ptXML);
}));
// Asynchronously initialize WebView2 when the custom dialog is ready
hostDlg.OpenXmlReceived += HostDlg_OpenXmlReceived;
};
hostDlg.ShowDialog();
});
// Set the thread to be STA
staThread.SetApartmentState(ApartmentState.STA);
// Start the STA thread
staThread.Start();
}
private void HostDlg_OpenXmlReceived(object sender, string openXml)
{
if (string.IsNullOrEmpty(openXml))
return;
m_OpenReturnString = openXml;
// Signal that the dialog has completed
//dialogCompletedEvent.Set();
CloseDialogAndExitThread(sender as HostDlg);
}
private void CloseDialogAndExitThread(HostDlg hostDlg)
{
// Close the dialog
hostDlg.CloseDialog();
//Signal the dialog completed event as it is now closed
dialogCompletedEvent.Set();
}
public HostDlg(int parentWindow)
{
Title = "Schedule";
Width = 1000;
Height = 500;
//WindowStartupLocation = WindowStartupLocation.;
ResizeMode = ResizeMode.NoResize;
//Topmost = true;
new WindowInteropHelper(this).Owner = (IntPtr)parentWindow;
//Content = CreateDialogContent(message);
}
The exception stack trace while calling ShowDialog() is:
at MS.Win32.UnsafeNativeMethods.CreateWindowEx(Int32 dwExStyle, String lpszClassName, String lpszWindowName, Int32 style, Int32 x, Int32 y, Int32 width, Int32 height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, Object pvParam)
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Interop.HwndSource.Initialize(HwndSourceParameters parameters)
at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
at System.Windows.Window.CreateSourceWindowDuringShow()
at System.Windows.Window.SafeCreateWindowDuringShow()
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()