Saturn
Saturn

Reputation: 18169

ToolStripButton = "Pressed"

I got a toolstripbutton, and when I click it, I want to make it stay "pressed" or "selected". Like a switch. And when I click another, make the pressed one "unpressed" again. Any ideas?

Upvotes: 3

Views: 4048

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

I think you want to use the CheckOnClick property. Set it to true, and the button should behave as you describe. In order to get (or set) the current state, use the Checked property.

Here is a full working sample:

public partial class Form1 : Form
{
    private readonly IEnumerable<ToolStripButton> mutuallyExclusiveButtons;

    public Form1()
    {
        InitializeComponent();
        mutuallyExclusiveButtons = new[] { firstButton, secondButton };
    }

    private void ToolStripButton_Click(object sender, EventArgs e)
    {
        ToolStripButton button = sender as ToolStripButton;
        if (button != null && button.Checked && 
            mutuallyExclusiveButtons.Contains(button))
        {
            foreach (ToolStripButton item in mutuallyExclusiveButtons)
            {
                if (item != button) item.Checked = !button.Checked;
            }
        }
    }
}

firstButton and secondButton are ToolStripButtons, both have CheckOnClick set to true, and their Clicked events hooked up to ToolStripButton_Click. This works also if there are more than two buttons in the group of buttons in which only one should be checked, just add any needed additional buttons to the mutuallyExclusiveButtons sequence.

Upvotes: 7

Fred
Fred

Reputation: 185

As ChrisF said, what you are looking for is the "Checked" property. (The "CheckOnClick" property is actually not what you want, since you want a sort of mutually exclusive toggle between two ToolStripButtons.)

What you will need is to put code (into the click event of each button) that will set the Checked property of that button to True and the Checked property of the other button to False.

Actually, you can use CheckOnClick and then add code only to set the other button to False.


(Hmmm... I wonder when the Checked becomes set to True; can you capture the MouseUp etc. event of BOTH buttons into one handler, and uncheck BOTH buttons, and then CheckOnClick will check the appropriate one later? Just some geek stuff to complicate things unnecessarily in the name of simplifying things)

Upvotes: 1

pjwilliams
pjwilliams

Reputation: 288

Maintain a flag as to what the status of a button is (pressed or normal). For each button press, call a method that refreshes the toolbar buttons to the correct state (either stay pressed or go back to normal).

Upvotes: -1

Related Questions