use*_*899 29 c# tabcontrol winforms
是否有人可以告诉我如何在C#中使用tabControl在每个选项卡中添加关闭按钮?我计划使用按钮图片替换我的标签中的[x] ..
谢谢
and*_*ted 56
在没有派生类的情况下,这里有一个简洁的片段:http: //www.dotnetthoughts.net/implementing-close-button-in-tab-pages/
将Tab控件的DrawMode属性设置为OwnerDrawFixed.此属性决定系统或开发人员是否可以绘制字幕.在Tab控件的DrawItem事件中添加代码 - 将调用此事件来绘制每个选项卡页面.
//This code will render a "x" mark at the end of the Tab caption.
e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right - 15, e.Bounds.Top + 4);
e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top + 4);
e.DrawFocusRectangle();
Run Code Online (Sandbox Code Playgroud)
现在,对于关闭按钮操作,我们需要将以下代码添加到Tab控件的MouseDown事件中.
//Looping through the controls.
for (int i = 0; i < this.tabControl1.TabPages.Count; i++)
{
Rectangle r = tabControl1.GetTabRect(i);
//Getting the position of the "x" mark.
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 9, 7);
if (closeButton.Contains(e.Location))
{
if (MessageBox.Show("Would you like to Close this Tab?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.tabControl1.TabPages.RemoveAt(i);
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
添加其他答案...为什么我们可以通过.SelectedIndex和.SelectedTab检测当前选项卡时,遍历鼠标单击事件的所有选项卡?
像这样:
private void tabControl1_MouseDown(object sender, MouseEventArgs e)
{
Rectangle r = tabControl1.GetTabRect(this.tabControl1.SelectedIndex);
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 9, 7);
if (closeButton.Contains(e.Location))
{
this.tabControl1.TabPages.Remove(this.tabControl1.SelectedTab);
}
}
Run Code Online (Sandbox Code Playgroud)
似乎发生的是,当您单击tabPage关闭它时,它也会被选中,从而允许关闭按钮关闭右侧tabPage.对我来说它有效,但请特别小心,因为我不完全确定可能的缺点(我的初始句子不是一个完全修辞的问题,因为我对.Net有点新鲜......).
| 归档时间: |
|
| 查看次数: |
64932 次 |
| 最近记录: |