简体   繁体   中英

C# Winfoms Toolstripdropdown close on button click

I have used toolstripdropdown in my Windows form to show list of buttons on click of another button.

var td = new ToolStripDropDown
        {
            AutoSize = true,
            DropShadowEnabled = false,
            BackColor = Color.Transparent,
            Margin = Padding.Empty,
            Padding = Padding.Empty
        };

        var host = new ToolStripControlHost(panel)
        {
            BackColor = Color.Transparent,
            Margin = Padding.Empty,
            Padding = Padding.Empty
        };

        td.Items.Add(host);

The panel contains list of buttons to be displayed. To show the panel to user, on button(Show) click following line is called.

td.Show(pointonScreen);

By default, AutoClose is set to true. So whenever user clicks anywhere in the form, the toolstripdropdown is getting closed. This is ok.

My requirements:

  1. Click Show button
  2. Display the toolstripdropdown by calling td.show() and close the popup if td.Visible
  3. Again click the Show button
  4. toolstripdrown should be closed
  5. Click anywhere in the form, toolstripdropdown should be closed if it is visible

What is happening now is, on step 3, before the button click event is raised, toolstripdropdown is getting closed. So again the dropdown is being displayed.

Is there any other way to achieve my requirements?

You should handle Closing event of the dropdown and set a flag if the dropdown is closing by click on the button which opened it. Then when you click on button, check the flag and if there wasn't a flag, show dropdown and set the flag, otherwise close the dropdown and clear the flag:

ToolStripDropDown td;
private void Form1_Load(object sender, EventArgs e)
{
    td = new ToolStripDropDown { /*...*/};
    var host = new ToolStripControlHost(this.panel1){ /*...*/};
    td.Items.Add(host);
    td.Closing += td_Closing;
}
void td_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
    if (e.CloseReason == ToolStripDropDownCloseReason.AppClicked)
        if (this.button1.Bounds.Contains(this.PointToClient(MousePosition)))
        {
            td.Tag = true;
            return;
        }
    td.Tag = null;
}
private void button1_Click(object sender, EventArgs e)
{
    if (td.Tag == null)
    {
        td.Show(Cursor.Position);
        td.Tag = true;
    }
    else
    {
        td.Close();
        td.Tag = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM