I've got a control that derives from Forms.Control, it handles mouse events and paint events just fine, but I'm having a problem with key events. I need to handle Left arrow and Right arrow, but so far the Tab control that contains my class eats these.
How do I make this control selectable, focusable?
Here is a nice tutorial to make a focusable control. I just followed it to make sure it works. Also, added a keypress event to the control which works on condition that the control has focus.
Basically all I did was make an instance of my custom control, which inherits from Control. Then added KeyPress, Click, and Paint event. Key press was just a message:
void CustomControl1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(string.Format("You pressed {0}", e.KeyChar));
}
Click event just has:
this.Focus();
this.Invalidate();
The paint event I made like this, just so it was visible:
protected override void OnPaint(PaintEventArgs pe)
{
if (ContainsFocus)
pe.Graphics.FillRectangle(Brushes.Azure, this.ClientRectangle);
else
pe.Graphics.FillRectangle(Brushes.Red, this.ClientRectangle);
}
Then, in the main form, after making an instance called mycustomcontrol and adding the event handlers:
mycustomcontrol.Location = new Point(0, 0);
mycustomcontrol.Size = new Size(200, 200);
this.Controls.Add(mycustomcontrol);
The example is much neater than my five minute code, just wanted to be sure that it was possible to solve your problem in this way.
Hope that was helpful.