Friday, June 15, 2012

Custom Controls in ToolStrip or StatusStrip

This is not something I have had to deal with too often which is why it wasn't apparent to me the first time around.

FACT: You cannot drag and drop a custom control or any System.Windows.Form.Control onto a System.Windows.Form.StatusStrip or System.Windows.Form.ToolStrip.

Aha! A gotcha! So how do you fix this problem? Well there are two options:

1. Make your own StatusStrip or ToolStrip item by inheriting from the System.Windows.Forms.ToolStripControlHost class.

Personally I don't like this method because it forces you to make a control that is only good for this purpose.

You can read more about it here.

Frankly I find the name of the article to be very misleading, you aren't really wrapping anything, you are creating a new class that inherits from the ToolStripControlHost. That's like saying making a custom control is a wrapper because it inherits from the Control class. Not so much...

2. Use this handy dandy methodology that apparently has been there all along, but I didn't find out about it until I stumbled across it yesterday during my google search. You simply need to add your custom control programmatically to your ToolStrip or StatusStrip by adding it as a ToolStripControlHost object.

Do Tell...

You simply do the following:
Dim myControl As SomeCustomControl = New SomeCustomControl()

'Perform operations on your control such as size, color, minimum size etc...

ToolStrip1.Items.Add(New ToolStripControlHost(myControl))
StatusStrip1.Items.Add(New ToolStripControlHost(myControl))

'If you are working with visbility, you will have to apply it to the ToolStripControlHost as well otherwise your control may not behave.

For the record I got all my info from this post here.

Please note there are sizing issues with this method and I haven't figured them all out yet. So this will require more research to figure out. If and when I figure it out I will be sure to mention it. Just make sure to set the size and the minimum size properties.

I prefer the second option over the first, but there is nothing wrong with the first either. I think that you get more re-usability out of the second option.

Forum Post about ToolStripControlHost

How to: Wrap a Windows Forms Control with ToolStripControlHost

No comments:

Post a Comment