Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c# - Close button in tabControl

is there anyone can tell me how to add close button in each tab in using tabControl in C#? i plan to use button pic for replacing [x] in my tab..

thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without deriving a class, here is a neat snippet: http://www.dotnetthoughts.net/implementing-close-button-in-tab-pages/

Set the DrawMode property of the Tab Control to OwnerDrawFixed. This property decides whether system or developer can paint the captions. Add the code in the DrawItem event of the Tab Control – This event will be invoked for painting each Tab Page.

    //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();

Now for close button action, we need to add the following code to the MouseDown event of the Tab Control.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...