专注还是不专注

To focus or not to focus

我有一个 PanelAutoScroll = true.

其中 Panel 是一系列 TextBoxes。我应该注意到 TextBoxes 不直接在 panel 上,而是嵌套了几个级别(大约 4-5)。

现在,只有当面板有焦点时,我的鼠标滚轮才能正常滚动。我可以在 mouseEnter 事件中使用 Focus() 来确保面板有焦点。

然而,我之前提到的 TextBoxes 严重依赖于焦点。只有用户才能通过单击其他地方从 TextBox 中移除焦点。

TextBoxes 是动态创建的,并且会产生非常混乱的代码来保存它们的数组,或任何类型的引用来检查它们是否具有焦点。更不用说它们可能有很多。

如何将焦点放在 Panel 上,但前提是 TextBoxes 的 none 是焦点?

您不需要保留动态创建的文本框的数组,您可以使用以下方法获取数组:

bool anyTextBoxFocused = false;
foreach (Control x in this.Controls)
{
  if (x is TextBox && x.Focused)
  {
       anyTextBoxFocused = true;
       break;
  }
}
if (!anyTextBoxFocused)
{
    //give focus to your panel
}

编辑

基于How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?,甚至嵌套控件也可以使用:

public IEnumerable<Control> GetAll(Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll(ctrl,type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

然后将其用于:

var c = GetAll(this,typeof(TextBox));