C# Winforms 在专注于 child 控制时失去焦点......有时

标签 c# winforms user-controls focus compact-framework

我正在开发一个 Windows Mobile 6.5 应用程序,当关注添加到表单的 UserControl 的子控件时,我的表单失去焦点时遇到问题......有时。

在我的应用程序中,我通过向主表单控件集合添加和删除用户控件来在屏幕之间导航。

IView nextView = (IView)Activator.CreateInstance(map.View);

this.Controls.Remove((UserControl)this.currentView);

this.currentView = nextView;

this.Controls.Add((UserControl)this.currentView);

因此,我在屏幕之间导航的基本流程是:

首先添加UserControl A

  1. 初始化用户控件A
  2. 将 UserControl A 添加到 Form.Controls
  3. 专注于 A 上的网格

导航到 UserControl B

  1. 初始化用户控件B
  2. 从 Form.Controls 中删除 UserControl A
  3. 将 UserControl B 添加到 Form.Controls

导航回 UserControl A

  1. 初始化用户控件A
  2. 从 Form.Controls 中删除 UserControl B
  3. 将 UserControl A 添加到 Form.Controls
  4. 专注于 A 上的网格

所有这一切工作正常,在第一次添加 UserControl A 时,表单获得焦点,子控件也获得焦点。

但是,当我从 UserControl B 导航回 UserControl A 时,表单失去了焦点,但前提是我在最后一步尝试将焦点放在子控件上。在我的应用程序中,这导致我无法使用手机硬件按钮在网格中导航。

知道为什么主窗体会失去焦点吗?

最佳答案

事实证明,当我导航回 UserControl A 时(我通过在方法中间触发导航事件来实现),UserControl B 中的代码继续执行,从而避免了对 UserControl A 的关注。

我曾希望当我从 Form.Controls 中删除 UserControl B(然后处置它)时,该方法的其余部分不会被执行,有点像 Response.Redirect 对 web 的作用。

我通过添加return解决了这个问题;触发 UserControl B 中的 OnNavigation 事件后的语句。

关于C# Winforms 在专注于 child 控制时失去焦点......有时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203381/

相关文章:

c# - 使用扩展方法复制数组

c# - 在哪里实例化表单?

c# - 在azure中托管共享dll

.net - 当我有表单事件时,为什么要使用 WndProc?

c# - .Net 用户控制界面

c# - 字符串中任何位置都不允许使用单词和字符的正则表达式,例如 ({}[]^)

c# - ASP.NET 核心 : Accessing appsettings from another project in solution

每次更改标签页时都会调用 C# WinForm DrawItem

c# - 为 Acumatica 创建自定义用户控件

c# - wpf中的多列自动搜索用户控件