我正在开发一个 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
- 初始化用户控件A
- 将 UserControl A 添加到 Form.Controls
- 专注于 A 上的网格
导航到 UserControl B
- 初始化用户控件B
- 从 Form.Controls 中删除 UserControl A
- 将 UserControl B 添加到 Form.Controls
导航回 UserControl A
- 初始化用户控件A
- 从 Form.Controls 中删除 UserControl B
- 将 UserControl A 添加到 Form.Controls
- 专注于 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/