如何在c#winforms中为选项卡页面设置关闭按钮的颜色
本文关键字:页面设置 关闭按钮 颜色 选项 c#winforms | 更新日期: 2024-09-19 11:47:08
我有一个选项卡控件,比如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);
如有任何帮助,我们将不胜感激。提前感谢
要在矩形中添加背景色,需要执行以下操作:
要绘制充满颜色的矩形,需要一个Graphics对象和从Brush派生的对象,例如SolidBrush或LinearGradientBrush。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);