问题
In a form I have a tab container in which I dynamically add tabs through the use of a button. As there is no easy way that I know of (then again I'm a WinForms newbie) to close the selected tab, I'd like to set up an event handler for handling a right click through which the tab will close. In simple words I want to right-click on the selected tab in order to close it.
This is the event handler which I have written (yet doesn't work):
private void tab_Click(object sender, EventArgs e)
{
MouseEventArgs me = (MouseEventArgs)e;
if (sender == tabControl1.SelectedTab && me.Button == MouseButtons.Right)
{
tabControl1.TabPages.Remove(tabControl1.SelectedTab);
}
}
I guess it's too naive of an approach? The handler does not even register the right click when I click on the tab. Any suggestions how to make this work?
回答1:
private void tabControl1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Application.Exit();
}
else
{
}
}
回答2:
You've got very iffy code here. Don't blindly cast an EventArgs object, simply use the MouseClick event instead. Don't blindly hope that the SelectedTab is the one that was clicked, that happen later. And never, never use the Remove() method like that, it is super-duper important to dispose the TabPage and its controls. If you don't then those controls will permanently leak, the kind of bug that eventually crashes your program with an undebuggable exception like "Error creating window".
Make it look like this instead:
private void tabControl1_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) {
for (int ix = 0; ix < tabControl1.TabCount; ++ix) {
if (tabControl1.GetTabRect(ix).Contains(e.Location)) {
tabControl1.TabPages[ix].Dispose();
break;
}
}
}
}
来源:https://stackoverflow.com/questions/33084104/add-a-right-click-event-to-a-tab-in-a-tabcontrol-container