C# Winfoms Toolstripdropdown close on button click

有些话、适合烂在心里 提交于 2019-11-29 22:59:34

问题


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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/36765715/c-sharp-winfoms-toolstripdropdown-close-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!