I'm working on a legacy application that uses WPF and WinForms for its UI. WPF makes up for the vast majority but the application main dialog is still in WinForms.
So far I've been able to have them work together nicely (thanks to System.Windows.Forms.Integration.ElementHost) but I can't get the WPF windows to center on their WinForms parent.
My code looks the following.
WPF Control (hosted in the ElementHost)
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var dialog = new SubWindow();
WindowOwnershipHelper.SetOwner(dialog, this);
dialog.ShowDialog();
}
OwnershipHelper (taken from https://stackoverflow.com/a/36606974/13567181)
This class establishes the 'parent-child' relationship so that nested dialogs open on the same screen and minimize together with their parent...
public static class WindowOwnershipHelper
{
public static void SetOwner(Window window, Visual parent)
{
var source = (HwndSource) PresentationSource.FromVisual(parent);
if (source == null)
{
throw new InvalidOperationException("Could not determine parent from visual.");
}
new WindowInteropHelper(window).Owner = source.Handle;
}
}
The problem that I'm facing is that when dialog.ShowDialog() executes, the newly opened window is not at all centered around its owner. It is somewhere on the screen but I don't quite understand how it determines its location.
Interestingly, if I repeat the ButtonBase_OnClick code inside the SubWindow class again, this new window is perfectly centered around its SubWindow parent.
From my point of view, this has something to do with the ElementHost parent of SubWindow.
Can someone advise me on how the get the SubWindow center around its parent without manually calculating its position? (similar to this https://stackoverflow.com/a/42401001/13567181)
EDIT: I just found this on MSDN - its somehow similar but I'm uncertain. https://social.msdn.microsoft.com/Forums/vstudio/en-US/05768951-73cf-4daf-b369-0905ca7e5222/centering-wpf-window-on-winforms-owner-window?forum=wpf
Best regards Norbert