原文: C# WPF 一直保持多個Topmost窗體的置頂順序
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/m0_37862405/article/details/80915523
參考自:
https://blog.csdn.net/okkk/article/details/44118469需求:多個窗體的Topmost都設定為true時候,還需要控制它們的置頂順序。
解決方法:結合窗體SourceInitialized事件和WindowInteropHelper類設定視窗所有者的句柄。在最後初始化的那個窗體的SourceInitialized事件中,設定視窗所有者的句柄。
例如:有兩個Topmost視窗:視窗A和視窗B,需要這兩個視窗都置頂顯示,并且,視窗A顯示在視窗B前面。這時候可以把視窗A的所有者設定為視窗B,因為子視窗(視窗A)會顯示在所有者視窗(視窗B)前面。
代碼:
//MainWindow 就是視窗A
public partial class MainWindow : Window
{
Window windowB;
public MainWindow()
{
InitializeComponent();
Topmost = true;
windowB = new Window { Topmost = true };
windowB.SourceInitialized += windowB_SourceInitialized;
}
private void windowB_SourceInitialized(object sender, EventArgs e)
{
//通過設定所有者,更改置頂順序
WindowInteropHelper helperA = new WindowInteropHelper(this);
WindowInteropHelper helperB = new WindowInteropHelper(windowB);
helperB.Owner = IntPtr.Zero;
helperA.Owner = helperB.Handle; //視窗A的所有者為視窗B,則視窗A顯示在最前面
//測試另外一種置頂順序
// helperA.Owner = IntPtr.Zero;
// helperB.Owner = helperA.Handle;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
windowB.Show();
}
}