C# Winfoms Toolstripdropdown close on button click

假如想象 提交于 2019-11-30 15:27:17

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