c# - WPF - 为什么窗口突然失去焦点?
问题描述
设想
考虑以下场景:您在 WPF 中启动一个应用程序。
- 主窗口打开(非模态)
Window1
(由 拥有MainWindow
) - 您将焦点更改为其他窗口(例如,Visual Studio)
- 在其他应用程序具有焦点的情况下,您按下一个按钮
Window1
- Window1 显示一个消息框
- 在其他应用程序具有焦点的情况下,您按下一个按钮
- 你关闭消息框
效果:您的主窗口突然低于您在第二步中选择的窗口。
图片:
步骤1
第2步
第 3 步
第4步
资料来源:
主窗口.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel Orientation="Vertical">
<TextBox />
<Button Content="Open window" Click="Button_Click" />
</StackPanel>
</Grid>
</Window>
主窗口.xaml.cs
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 window1 = new Window1();
window1.Owner = this;
window1.Show();
}
}
}
Window1.xaml
<Window x:Class="WpfApp1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800" ShowInTaskbar="False">
<Grid>
<Button Click="Button_Click"/>
</Grid>
</Window>
Window1.xaml.cs
namespace WpfApp1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Test");
Close();
}
}
}
问题
从另一个窗口关闭消息框后如何在主窗口中保持焦点?
解决方案
推荐阅读
- local-storage - 从网站检查和删除 google_experiment_mod 的位置
- javascript - 如何创建每分钟发出哔哔声的秒计数器
- php - PHP 未定义的偏移量(不是错误)try catch
- performance - “共享”或“缓存”仅由不明确类型参数化的表达式?
- java - 用两个 web.xml 部署 war
- javascript - 测试蛇是否与自身发生碰撞的功能将不起作用
- javascript - 如何获取对象数组并根据属性值创建数组?
- scala - fs2 流:测试 fs2 服务器
- google-cloud-platform - 用于 Web UI 更新的 Google Pub/Sub?
- jupyter-notebook - 防止代码单元在将 Jupyter Lab 导出为 HTML 后换行文本