I am developing an application in C# using WinUI3 and I am having trouble setting the parent window for a modeless dialog. By setting the parent window, I expect the following effects:
- The dialog should be displayed in front of the parent window.
- The dialog should close when the parent window is closed.
Here is the code I have tried. I used SetParent, but the dialog gets embedded within the main window, and the AppWindow of the dialog becomes null.
public sealed partial class ModelessDialog : Window
{
public ModelessDialog(SizeInt32 windowSize, Window _parent)
{
this.InitializeComponent();
OverlappedPresenter presenter = (OverlappedPresenter)this.AppWindow.Presenter;
presenter.IsResizable = true;
this.AppWindow.SetPresenter(presenter);
this.AppWindow.IsShownInSwitchers = false;
this.AppWindow.Resize(windowSize);
IntPtr windowHandle = App.GetWindowHandle(this);
IntPtr parentHandle = App.GetWindowHandle(_parent);
SetParent(windowHandle, parentHandle);
}
public IntPtr GetWindowHandle(in Window _window)
{
return WinRT.Interop.WindowNative.GetWindowHandle(_window);
}
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
}
I am developing an application in C# using WinUI3 and I am having trouble setting the parent window for a modeless dialog. By setting the parent window, I expect the following effects:
- The dialog should be displayed in front of the parent window.
- The dialog should close when the parent window is closed.
Here is the code I have tried. I used SetParent, but the dialog gets embedded within the main window, and the AppWindow of the dialog becomes null.
public sealed partial class ModelessDialog : Window
{
public ModelessDialog(SizeInt32 windowSize, Window _parent)
{
this.InitializeComponent();
OverlappedPresenter presenter = (OverlappedPresenter)this.AppWindow.Presenter;
presenter.IsResizable = true;
this.AppWindow.SetPresenter(presenter);
this.AppWindow.IsShownInSwitchers = false;
this.AppWindow.Resize(windowSize);
IntPtr windowHandle = App.GetWindowHandle(this);
IntPtr parentHandle = App.GetWindowHandle(_parent);
SetParent(windowHandle, parentHandle);
}
public IntPtr GetWindowHandle(in Window _window)
{
return WinRT.Interop.WindowNative.GetWindowHandle(_window);
}
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
}
Share
Improve this question
edited Mar 18 at 2:52
Andrew KeepCoding
14.2k2 gold badges21 silver badges37 bronze badges
asked Mar 18 at 1:49
kintonkinton
3151 silver badge7 bronze badges
1 Answer
Reset to default 1You can use the parent's Closed event to close the modeless window.
public partial class ModelessWindow : Window
{
public ModelessWindow(SizeInt32 size, Window parent) : base()
{
parent.Closed += (s, e) => this.Close();
this.AppWindow.MoveAndResize(
new RectInt32(
parent.AppWindow.Position.X,
parent.AppWindow.Position.Y,
size.Width,
size.Height));
}
}