Sunday, June 14, 2009

Remove Focus Rectangle From Button

Article is about to remove focus rectangle or say cues from Button in window form application.

First let discuss what default focus rectangle. Please look at following image , in that image OK button has default focus so it display cues rectangle.

image 
(FlatStyle == System)

When we want to set background image of button to make button attractive in that case this default rectangle create problem with look and feel.

image
(FlatStyle = Standard)
 
 image
(FlatStyle = Flat)

In above two image need to set FlatApperance.BorderStyle =0. You can visualize that in all above case default focus rectangle make button look ugly with background image.

To remove this cues ( Default focus rectangle ) you need to set ShowFocusCues property of Button to false but this property does not directly available to Button. This property available in ButtonBase class with protected access specifier. In order to set this property to false we need to create class that inherits from Button or ButtonBase and set this property explicitly false.

class CustomButton : System.Windows.Forms.Button
    {
        protected override bool ShowFocusCues
        {
            get
            {
                return false;
            }
        }
}

image
Now see that default focus rectangle is removed.

More generic class for Button.

class CustomButton : System.Windows.Forms.Button
   {
       private bool _DisplayFocusCues = true;
       protected override bool ShowFocusCues
       {
           get
           {
               return _DisplayFocusCues;
           }
       }

       public bool DisplayFocusCues
       {
           get
           {
               return _DisplayFocusCues;
           }
           set
           {
               _DisplayFocusCues = value;
           }
       }
   }

Using this class you can set DisplayFocusCues at design time so CustomButton work with any case. ( Want to display focus rectangle or not).

image 

Hope this solution is help you to create button without cues.

Your suggestion is always invited.

8 comments:

Anonymous said...

Thank You!!! It really works and your explanation is simple and clear.

Anonymous said...

Thanks. One question though, is it possible to do this in ASP Button? How do we do it? Thank you.

Jangid said...

How to add this control to the from

Anonymous said...

Thank You so much. It's very useful to me.

Anonymous said...

Thanks a lot!!... Im looking for this!!

Anonymous said...

thanks :)

Anonymous said...

Hi,

How do you implement the code into the MSVS so the focus option is avail. in the properties pane??

regards,

ger

dotnetstep said...

I implemented as properties of inherited control so it displayed in property pane.