How do I programmatically wire up ToolStripButton events in C#?

こ雲淡風輕ζ 提交于 2019-12-17 21:32:19

问题


I'm programmatically adding ToolStripButton items to a context menu.

That part is easy.

this.tsmiDelete.DropDownItems.Add("The text on the item.");

However, I also need to wire up the events so that when the user clicks the item something actually happens!

How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.


回答1:


Couldn't you just subscribe to the Click event? Something like this:

ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);

And OnBtnClicked would be declared like this:

private void OnBtnClicked(object sender, EventArgs e)
{
    ToolStripButton btn = sender as ToolStripButton;

    // handle the button click
}

The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.




回答2:


Thanks for your help with that Andy. My only problem now is that the AutoSize is not working on the ToolStripButtons that I'm adding! They're all too narrow.

It's rather odd because it was working earlier.


Update: There's definitely something wrong with AutoSize for programmatically created ToolStripButtons. However, I found a solution:

  1. Create the ToolStripButton.
  2. Create a label control and set the font properties to match your button.
  3. Set the text of the label to match your button.
  4. Set the label to AutoSize.
  5. Read the width of the label and use that to set the width of the ToolStripButton.

It's hacky, but it works.



来源:https://stackoverflow.com/questions/84842/how-do-i-programmatically-wire-up-toolstripbutton-events-in-c

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