Creating a Tool Strip Toggle Button

A toggle button is a button that has two states—and ordinary unselected state and a selected state. When a toggle button is in its selected state, it remains highlighted even when the mouse is not hovering over it. The user can turn a toggle button on or off by clicking it once.

Toggle buttons are easy with the ToolStrip because the ToolStripButton class adds several properties for managing them. The selected state is known as checked, and the ToolStripButton adds a Checked property that, if true, highlights the item permanently. To add the on/off behavior, you simply set the CheckOnClick property to true. That way, the button is automatically switched on or off when the user clicks it. Finally, you can use the CheckedChanged event to react in your code when the button is selected or unselected.

Some toggle buttons are used in groups. For example, in Microsoft Word there are a set of justification buttons, and only one can be selected at a time. To implement this design, the CheckOnClick property isn't enough—instead, when a button in the group is clicked you need to handle the CheckedChanged event, and manually set the Checked property of the other buttons to false.

+3 -1

Post a comment