Как правильно установить цвет фона в области заголовка TabControl в C# Winforms?C#

Место общения программистов C#
Ответить
Anonymous
 Как правильно установить цвет фона в области заголовка TabControl в C# Winforms?

Сообщение Anonymous »

Я пытаюсь создать табконтрол на тарелке в моем приложении C# Winforms. Моя цель состоит в том, чтобы установить весь фон форматов и границы и табконтроля темно -серому цвету (#484848). < /P>
Я установил модуру моего TabControl на Tabdrawmode.ownderDrawfix, и я обрабатываю событие Drawitem, чтобы настроить внешний вид каждого вкладка. Это работает для раскраски индивидуальных кнопок вкладок. На изображении ниже показана проблема: Стрелки указывают на фон заголовка и пустое пространство, которое я хочу раскрасить # 484848, но которые остаются белыми.
randling handling the handling the handling the handling ailling handling ailing a i randling handling ailling ailing a i the randling houtsling. Событие TabControl покраски, чтобы вручную заполнить фон заголовка, но, похоже, он не имеет желаемого эффекта. Цвет фона вкладок устанавливается правильно, но фон панели заголовка является проблемой.public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
this.BackColor = ColorTranslator.FromHtml("#484848");

// Set up the TabControl for custom drawing
this.tabmenu.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabmenu.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabmenu_DrawItem);

// This attempt to paint the background doesn't seem to solve the issue with the header area
this.tabmenu.Paint += Tabmenu_Paint;

// Set background color for all tab pages
SetTabPageBackgroundColors();
}

private void SetTabPageBackgroundColors()
{
foreach (TabPage tabPage in this.tabmenu.TabPages)
{
tabPage.BackColor = ColorTranslator.FromHtml("#484848");
}
}

// This is my attempt to paint the entire background of the TabControl,
// but the area behind the tabs remains white.
private void Tabmenu_Paint(object sender, PaintEventArgs e)
{
TabControl tabControl = sender as TabControl;
if (tabControl == null) return;

Color headerBackgroundColor = ColorTranslator.FromHtml("#484848");

using (SolidBrush headerBrush = new SolidBrush(headerBackgroundColor))
{
// This rectangle should cover the entire header area, but it doesn't work as expected.
Rectangle headerRect = new Rectangle(0, 0, tabControl.Width, tabControl.ItemSize.Height + 2);
e.Graphics.FillRectangle(headerBrush, headerRect);
}
}

// This method correctly paints the individual tab items.
private void tabmenu_DrawItem(object sender, DrawItemEventArgs e)
{
TabControl tabControl = sender as TabControl;
TabPage page = tabControl.TabPages[e.Index];

// Define colors
Color tabBackgroundColor = ColorTranslator.FromHtml("#484848");
Color activeTextColor = Color.White;
Color inactiveTextColor = Color.LightGray;

// Determine text color based on selection state
Color textColor = (e.State & DrawItemState.Selected) == DrawItemState.Selected ? activeTextColor : inactiveTextColor;

// Paint the background of the tab button
using (SolidBrush backgroundBrush = new SolidBrush(tabBackgroundColor))
{
e.Graphics.FillRectangle(backgroundBrush, e.Bounds);
}

// Draw the tab text
using (SolidBrush textBrush = new SolidBrush(textColor))
{
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
e.Graphics.DrawString(page.Text, this.Font, textBrush, e.Bounds, sf);
}
}

// Other form-related code (resizing, etc.) is omitted for brevity.
}
< /code>
Любая помощь в том, что я могу сделать неправильно, или какой правильный подход будет высоко оценен. Спасибо!

Подробнее здесь: https://stackoverflow.com/questions/797 ... -in-c-shar
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»