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.
I've searched around but haven't found any info on creating my own Event Handlers for the Label Control. Can this be done is 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.
If you really need something like that, you should spoof a TextBox
with the following settings as starting point:
textBox1.BorderStyle = BorderStyle.None;
textBox1.Cursor = Cursors.Default;
textBox1.ReadOnly = true;
textBox1.TabStop = false;
textBox1.Text = "foo";
Another possibility is described here.
I did the following in the Constructor:
SetStyle(ControlStyles.Selectable, true);
and also override the OnMouseDown method:
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...
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. 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.
Actually, Label
inherits from Control
, so it has a KeyDown
event. 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.
精彩评论