WPF主窗口在关闭子窗口后置于后台
我开发了一个WPF项目示例。WPF主窗口在关闭子窗口后置于后台,wpf,window,Wpf,Window,我开发了一个WPF项目示例。 以下是主窗口的隐藏代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Docum
以下是主窗口的隐藏代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
namespace MainWindowInBackground
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window l_hostWindow = new Window()
{
Owner = System.Windows.Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Content = "Test"
};
l_hostWindow.Show();
Window l_hostWindow2 = new Window()
{
Owner = System.Windows.Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Content = "Test 2"
};
l_hostWindow2.Show();
l_hostWindow2.Close();
//MessageBox.Show(this, "MessageBox", "MessageBox", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用Telerik.Windows.Controls;
命名空间MainWindowInBackground
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
窗口l_主机窗口=新窗口()
{
所有者=System.Windows.Application.Current.MainWindow,
WindowsStartUplocation=WindowsStartUplocation.CenterOwner,
Content=“测试”
};
l_hostWindow.Show();
窗口l_hostWindow2=新窗口()
{
所有者=System.Windows.Application.Current.MainWindow,
WindowsStartUplocation=WindowsStartUplocation.CenterOwner,
Content=“测试2”
};
l_hostWindow2.Show();
l_hostWindow2.Close();
//MessageBox.Show(这个“MessageBox”、“MessageBox”、MessageBoxButton.OK、MessageBoxImage.Information、MessageBoxResult.OK);
}
}
}
当用户单击按钮时:
- 我已经启动了这个应用程序。动作后拍摄的屏幕截图:
- 我已经点击了按钮。此时将显示R1窗口。动作后拍摄的屏幕截图:
- 我把窗户关上了。主窗口已自动置于后台。动作后拍摄的屏幕截图:
提前感谢您的帮助无法告诉您为什么会将其发送到后台,但将其保持在前台并聚焦的方法是使其成为子窗口的所有者,并在子窗口关闭时调用父窗口的
Window.Focus()
方法
public ChildWindow()
{
InitializeComponent();
Owner = Application.Current.MainWindow;
}
private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
if (Owner == null) return;
Owner.Focus();
}
尝试设置
childWindow.Owner=Application.Current.MainWindow代码>。