c# - 重新着色 TabControl

标签 c# .net winforms colors tabs

我有一个想要自定义的选项卡控件。更具体地说,我想更改标签页标题的颜色,以及标签页周围白线的颜色(检查第一张图片)。

我想过使用自定义渲染器来执行此操作(例如,类似于重新着色菜单条),但我不确定如何执行此操作。我还读到,将 DrawMode 设置为 OwnerDrawFixed 可以做到这一点,但使用此选项会使选项卡控件看起来好像我的程序是在 90 年代制作的(检查第二张图片)。

我真正想做的是保持选项卡简单和平改变它们的颜色。以 Visual Studio 中选项卡的方式为例(检查第三张图片)。

enter image description here

有什么想法吗?

编辑:标签页的另一张图片,以便更清楚这条“白线”是什么。

enter image description here

最佳答案

当您使用OwnerDrawFixed时,这意味着将提供绘图代码。如果您没有连接并使用 DrawItem 事件,则不会绘制任何内容。这看起来与设计时的非常相似,因为事件没有触发。对于设计时绘画,您必须对控件进行子类化并使用 OnDrawItem

   // colors to use
   private Color[] TColors = {Color.Salmon, Color.White, Color.LightBlue};

   private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
   {
       // get ref to this page
       TabPage tp = ((TabControl)sender).TabPages[e.Index];

       using (Brush br = new SolidBrush(TColors[e.Index]))
       {
           Rectangle rect = e.Bounds;
           e.Graphics.FillRectangle(br, e.Bounds);

           rect.Offset(1, 1);
           TextRenderer.DrawText(e.Graphics, tp.Text, 
                  tp.Font, rect, tp.ForeColor);

           // draw the border
           rect = e.Bounds;
           rect.Offset(0, 1);
           rect.Inflate(0, -1);

           // ControlDark looks right for the border
           using (Pen p = new Pen(SystemColors.ControlDark))
           {
               e.Graphics.DrawRectangle(p, rect);
           }

           if (e.State == DrawItemState.Selected) e.DrawFocusRectangle();
        }
   }

基本结果:

enter image description here

标签拇指对我来说看起来有点局促,而且没有默认的那么高。因此,我添加了 TFontSize 来以与字体不同的大小绘制文本。

TabControl.Font设置为10(这似乎足够了),以便Windows绘制稍大的拇指/标题。如果您仍然以默认的 8.25 绘制文本,则还有更多空间:

   private float TFontSize = 8.25F;       // font drawing size
   ...
   using (Font f = new Font(tp.Font.FontFamily,TFontSize))
   {
       // shift for a gutter/padding
       rect.Offset(1, 1);                  
       TextRenderer.DrawText(e.Graphics, tp.Text, 
                     f, rect,  tp.ForeColor);
   }

enter image description here

通过这种方式,您将失去的一件事是 VisualStyles 效果,但无论如何它们似乎都会与彩色选项卡发生冲突。

关于c# - 重新着色 TabControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822870/

相关文章:

c# - System.Device.Location.GeoCooperativeWatcher.Position.Location.Speed 始终为 NaN

C# BotFrameWork Q & A Maker,你的意思是回复吗?

c# - .NET CLR 是否预先计算属性值?

winforms - 如何使ReactiveCommand同步?

.net - 如何让winform窗口透明且图片可见?

c# - 将控件对齐到 FlowLayout 的中心

c# - Entity Framework 查询无法使用 asp.net

c# - 跳过等待任务响应条件

c# - 在警报对话框中单击按钮时重定向

c# - 在使用回调关闭连接时收到 WCF 异常