Alex Rivera | Logout

Do I really have to call Focus in OnMouseDown of my custom Control?

Asked 2010-03-27T12:29:01.230
10

I'm implementing a custom control that inherits from Control. I want it to be focusable (it's a kind of list box).

In the constructor, I do

SetStyle(ControlStyles.Selectable, true);

I can now use Tab to navigate to the control.

However, when the control receives a mouse click, it does not automatically claim focus. I can work around this, of course:

protected override void OnMouseDown(MouseEventArgs e)
{
    Focus();
    base.OnMouseDown(e);
}

But this feels like a kludge that should not be necessary. Is this really the way to go? Or is there some way to tell Control to claim focus automatically when it receives a mouse click?

Edit
Report

1 Answer

0
  1. compile in a WinForms project for FrameWork 3.5

  2. drag an instance of Control1 from the ToolBox to a Form Surface ... make sure its TabStop property is set to 'true

  3. put some other controls on the form.

  4. verify that when the instance of Control1 is tabbed to: it shows a selection rectangle which disappears as you "tab away" from it.

  5. verify if you click on the instance of Control1 that it shows the selection rectangle, and if you click on some other control it disappears.

    namespace testFocusableControl
    {
        //  VS Studio 2010 RC1 : Tested against FrameWork 3.5 Full (not 'Client)
    
        public class Control1 : Control
        {
            public Control1()
            {
                SetStyle(ControlStyles.UserMouse, true);
            }
    
            protected override void OnLostFocus(EventArgs e)
            {
                this.Invalidate();
                base.OnLostFocus(e);
            }
    
            protected override void OnGotFocus(EventArgs e)
            {
                this.Invalidate();
                base.OnGotFocus(e);
            }
    
            protected override void OnPaint(PaintEventArgs e)
            {
                if (this.Focused)
                {
                    ControlPaint.DrawFocusRectangle(e.Graphics, this.ClientRectangle, Color.Red, Color.Blue);
                }
                base.OnPaint(e);
            }
        }
    }
    

The only "loose end" here for me is that this solution will show the selection rectangle on a mouse-click, but I did not implement any MouseDown code as Thomas suggested.

Note that if you make the Control above a 'ContainerControl via 'SetStyle(ControlStyles.ContainerControl, true); and add some other control to it, even if you set the TabStop property of the added control to 'false : ... if it clicked ... it will get focus, and you will lose the focus rectangle shown on the ContainerControl.

answered 2010-03-30T09:02:11.983

Your Answer