views:

258

answers:

4

Hi All

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

+1  A: 

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 Labels aren't intended to receive focus, so said event normally wouldn't fire.

R. Bemrose
That is true, thank you for reminding me! I have come up with a solution myself and will post the solution once I've finished testing it.
lucifer
+3  A: 

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.

Oliver
A: 

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.

Andy Shellam
+1  A: 

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...

Abel