David Rutten
David Rutten

Reputation: 4806

Windows.Forms.Control derived class with TabStop and key-events

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?

Upvotes: 0

Views: 1108

Answers (3)

Brandi
Brandi

Reputation: 1579

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.

http://en.csharp-online.net/Architecture_and_Design_of_Windows_Forms_Custom_Controls%E2%80%94Creating_a_Focusable_Control

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.

Upvotes: 2

TheHurt
TheHurt

Reputation: 1610

Without seeing your code, I can only tell you that I created a 3 tab container, and created a very simple control that overrode the OnGotFocus:

public partial class CustomControl1 : Control
{
    public CustomControl1()
    {
        InitializeComponent();
    }

    protected override void OnGotFocus(EventArgs e)
    {
        this.BackColor = Color.Black;
        base.OnGotFocus(e);
    }
    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }
}

I dropped the control on the form along with a couple of other buttons, set the tab stops appropriately, and the behavior was as expected. Some other default property has been changed in code that is causing the control to not be selectable.

Upvotes: 1

Jeff Yates
Jeff Yates

Reputation: 62367

In order to be selectable, your control has to have the ControlStyles.Selectable style set. You can do this in the constructor by calling SetStyle.

Upvotes: 1

Related Questions