简体   繁体   English

为Label Control创建KeyDown事件处理程序

[英]Creating a KeyDown Event Handler for the Label Control

I'm sure you're all aware of the fact that the Label Control has no KeyDown handler (and why would it?)... Anyway, I'm in need of a KeyDown handler for the Label Control and would appreciate any pointers/suggestions to get me started. 我确定你们都知道Label Control没有KeyDown处理程序(为什么会这样?)......无论如何,我需要一个Label Control的KeyDown处理程序,并且会欣赏任何指针/建议让我开始。

I've searched around but haven't found any info on creating my own Event Handlers for the Label Control. 我已经四处搜索,但没有找到任何有关为Label Control创建自己的事件处理程序的信息。 Can this be done is C#? 这可以做到C#?

Thanks 谢谢

The problem starts far earlier. 问题开始的时间要早​​得多。 A label is not able to got a focus event. 标签无法获得焦点事件。 So it never has a focus and therefore never receives a KeyDown event. 因此它永远不会有焦点,因此永远不会收到KeyDown事件。

If you really need something like that, you should spoof a TextBox with the following settings as starting point: 如果你真的需要这样的东西,你应该用以下设置欺骗TextBox作为起点:

textBox1.BorderStyle = BorderStyle.None;
textBox1.Cursor = Cursors.Default;
textBox1.ReadOnly = true;
textBox1.TabStop = false;
textBox1.Text = "foo";

Another possibility is described here . 这里描述另一种可能性。

A Label isn't designed to receive input from a user, so as others have pointed out it cannot get focus or the Key* events. Label不是为了接收来自用户的输入而设计的,因为其他人已经指出它无法获得焦点或Key *事件。 If you did manage to get this working, it wouldn't be obvious to users because they cannot click on the label to give it focus to start typing. 如果您确实设法使其正常工作,那么用户就不会明白这一点,因为他们无法点击标签以使其专注于开始输入。

Perhaps if you explain more what you're trying to achieve someone may suggest an alternative. 也许如果你解释更多你想要实现的目标,有人可能会提出另一种选择。

I did the following in the Constructor: 我在构造函数中执行了以下操作:

SetStyle(ControlStyles.Selectable, true); SetStyle(ControlStyles.Selectable,true);

and also override the OnMouseDown method: 并重写OnMouseDown方法:

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (this.CanSelect) this.Select();
}

After doing that your control should receive Keyboard events. 完成后,您的控件应该接收键盘事件。 But if you want to create a TextBox like control out of a label, it will be a lot of work... 但是如果你想从标签中创建一个类似控件的TextBox,那将是很多工作......

Actually, Label inherits from Control , so it has a KeyDown event. 实际上, Label继承自Control ,因此它有一个KeyDown事件。 It's just that Visual Studio isn't showing it in the GUI, because Label s aren't intended to receive focus, so said event normally wouldn't fire. 只是Visual Studio没有在GUI中显示它,因为Label不是为了获得焦点,所以所述事件通常不会触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM