【问题标题】:How to set the color of a close button for a tab page in c# winforms如何在c#winforms中为标签页设置关闭按钮的颜色
【发布时间】:2015-03-02 06:15:24
【问题描述】:

我有一个选项卡控件说 tabMain 。在我的主页选项卡的第一个选项卡中,我有一个下拉菜单和一个添加按钮。当我单击添加按钮时,将打开一个新选项卡,其中所选项目作为选项卡标题。除了选项卡标题,我还需要包含一个关闭按钮。现在我有关闭按钮但我还需要为关闭按钮设置背景颜色。这是我的代码的一部分。

 TabPage newTabPage= new TabPage();   
 newTabPage.Text = cmbType.SelectedItem.ToString() +"  X";
 tabMain.TabPages.Add(newTabPage);

在我的鼠标按下事件中,我已经包含了关闭函数。

 private void tabMain_MouseDown(object sender, MouseEventArgs e)
    {
        try
        {                
            if (tabMain.SelectedIndex > 0)
            {
                Rectangle r = tabMain.GetTabRect(tabMain.SelectedIndex);                    
                Rectangle closeButton = new Rectangle(r.Right - 15, r.Y, 15, 18);

                if (closeButton.Contains(e.Location))
                {
                    if (MessageBox.Show("Would you like to Close this Tab?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        this.tabMain.TabPages.RemoveAt(tabMain.SelectedIndex);
                    }
                }
            } 
        }
        catch(Exception)
        {
            MessageBox.Show("Exception in closing a tab");
        }
    }

我的关闭按钮工作正常。但我需要为关闭按钮设置颜色。我也试过包括一个标签。这是代码

TabPage newTabPage = new TabPage();                
Label labelClose = new Label();
labelClose.Text = "  X";
labelClose.BackColor = System.Drawing.Color.Red;               
newTabPage.Text = cmbType.SelectedItem.ToString() + labelClose.Text;
tabMain.TabPages.Add(newTabPage); 

任何帮助将不胜感激。 提前致谢

【问题讨论】:

  • 你没有关闭按钮,你有一个名为 closeButton 的矩形,它有点模仿按钮。如果您想要一个关闭按钮并想要为其着色,请使用一个真正的按钮,并将一个事件处理程序附加到单击事件。此代码将比您尝试做的要简单得多。
  • @PhilipStuyck : 是的..你是对的..我也可以添加一个按钮关闭..但是虽然我添加了一个按钮,但如何仅为它设置颜色?
  • 当然,通过它的属性,一旦您使用普通按钮,您的问题就会变得非常简单。查看您自己设置标签背景颜色的代码。
  • 您应该自定义绘制您的选项卡控件。这个link 可以帮助你。还要检查这个link
  • 或移至 WPF,在选项卡标题中添加按钮要容易得多。问题是你真的想要那个标题中的按钮吗?

标签: c# winforms tabcontrol tabpage


【解决方案1】:

要为矩形添加背景颜色,您需要执行以下操作:

要绘制一个充满颜色的矩形,您需要一个 Graphics 对象和 从 Brush 派生的对象,例如 SolidBrush 或 线性渐变画笔。 Graphics 对象提供 FillRectangle 方法和 Brush 对象提供颜色和填充信息。

//Create graphic object for the current form
Graphics gs = this.CreateGraphics();
//Create a rectangle object
Rectangle closeButton = new Rectangle(r.Right - 15, r.Y, 15, 18);
//Fill the rectangle with red color
gs.FillRectangle(new SolidBrush(Color.Red), closeButton);

【讨论】:

  • 谢谢。但它有帮助..我也已经尝试过了..但它不起作用。 :(
  • Graphics 是一次性对象,使用 using 机制或完成后处理图形对象。
猜你喜欢
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多