【问题标题】:Make label participate in control tabbing使标签参与控制标签
【发布时间】:2013-08-01 23:40:42
【问题描述】:

我有继承自Label 的自定义控件,并将ControlStyle.Selectable 设置为true。

当用户点击该控件时,它会获得焦点,但如果用户从另一个控件中选择选项卡则不会。

即使我有一个仅由该类型控件填充的表单,它们也没有通过 Tab 键获得焦点。

如何让我的Label 通过 Tab 键获得焦点?

【问题讨论】:

  • Selectable 不是 TabStop。不同的属性。

标签: c# winforms user-controls


【解决方案1】:

将其设为TextBox 可能更容易,将BorderStyle 设置为None,将BackColor 设置为Control 并将ReadOnly 设置为True。这应该给出一个标签的外观,但仍然允许它被标记为焦点。

更新 看起来像SetStyle(ControlStyles.Selectable, true); 和TabStop = true; 的组合,您可以使用Tab 键使标签聚焦。下面是一个简单的例子,展示了它的工作原理:

public class SelectableLabel : Label
{
   public SelectableLabel()
   {
      SetStyle(ControlStyles.Selectable, true);
      TabStop = true;
   }

   protected override void OnEnter(EventArgs e)
   {
      BackColor = Color.Red;
      base.OnEnter(e);
   }

   protected override void OnLeave(EventArgs e)
   {
      BackColor = SystemColors.Control;
      base.OnLeave(e);
   }

   protected override void OnMouseDown(MouseEventArgs e)
   {
      this.Focus();
      base.OnMouseDown(e);
   }
}

【讨论】:

    【解决方案2】:

    将属性 Control.TabStop 设置为 true

    【讨论】:

    • 根据 Label、The TabStop property is not relevant for the Label class, so setting TabStop to true has no effect. 的 msdn 文档
    • 我读过同样的东西,但不知何故它起作用了,也许与 ControlStyle.Selectible 联合。
    • @user629926 有效吗?你用的是哪个VS版本?在 VS 2010 中它不起作用!
    • 是的,看起来可能是组合,@Hans Passant 为面板 here 发布了类似的解决方案
    • @SwDevMan81 OP 已经接受了你的。即使在其初步版本(只是转换为文本框)中,它也是正确的,我做了+1。对不起 rajeem_cariazo,但我想他也想因正确答案而获奖,而这个答案不对。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 2020-07-24
    • 2019-06-14
    • 2014-06-13
    相关资源
    最近更新 更多