【问题标题】:C# Winforms form losing focus when focusing on child control ... sometimesC# Winforms 在关注子控件时失去焦点......有时
【发布时间】:2013-08-13 07:44:59
【问题描述】:

我正在开发一个 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. 初始化 UserControl A
  2. 将 UserControl A 添加到 Form.Controls
  3. 关注 A 上的网格

导航到用户控件 B

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

导航回 UserControl A

  1. 初始化 UserControl A
  2. 从 Form.Controls 中删除 UserControl B
  3. 将 UserControl A 添加到 Form.Controls
  4. 关注 A 上的网格

所有这些都可以正常工作,并且在第一次添加 UserControl A 时,表单具有焦点,子控件也具有焦点。

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

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

【问题讨论】:

  • 为什么要删除/添加 this.currentView?
  • 只是一种预感,但也许尝试在删除旧视图之前添加新视图,以便在表单上始终有一个可聚焦的控件。
  • 您可以使用作为 Visual Studio 2008 远程工具一部分的 Remote SPY 连接到应用程序。此工具可帮助您捕获 WM_SETFOCUS 和 WM_KILLFOCUS 消息。也许这有助于更好地了解情况。请给我们看一下 Focus 代码。

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


【解决方案1】:

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

我曾希望当我从 Form.Controls 中删除 UserControl B(然后将其释放)时,不会执行该方法的其余部分,就像 Response.Redirect 对 web 所做的那样。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多