使用Paint事件重畫GroupBox來修改邊框顏色


在.Net下進行WinForm開發,GroupBox是經常要用到的一個控件。但是GroupBox自身的邊框是灰白色的,其樣式很難令開發者滿意。在不借用第三方控件的情況下,通過其的Paint事件對GroupBox進行重畫,也可以很方便的修改其邊框顏色/樣式。

  簡要說一下實現思路。首先用Clear方法清除GroupBox的顯示,接着再用合適的樣式把GroupBox畫出來。把GroupBox拆分為4個圓角,一行標題文字和數段直線等元素,把這些元素擺放在合適的位置,拼湊出GroupBox的外框。定義4個Rectangle(用於后面的畫圓角),確定它們的大小和位置;然后在確切的位置上畫4個弧段,按圓角在GroupBox上的位置確定其角度;接着在對應的位置畫出GroupBox標題和幾條直線,就大功告成了。只需簡單修改代碼中的設置顏色語句,便可以完成GroupBox邊框顏色的更換了。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
  
namespace WindowsApplication2
{
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
  
         private void groupBox1_Paint( object sender, PaintEventArgs e)
         {
             e.Graphics.Clear(groupBox1.BackColor);
  
             Rectangle Rtg_LT = new Rectangle();
             Rectangle Rtg_RT = new Rectangle();
             Rectangle Rtg_LB = new Rectangle();
             Rectangle Rtg_RB = new Rectangle();
             Rtg_LT.X = 0; Rtg_LT.Y = 7; Rtg_LT.Width = 10; Rtg_LT.Height = 10;
             Rtg_RT.X = e.ClipRectangle.Width - 11; Rtg_RT.Y = 7; Rtg_RT.Width = 10; Rtg_RT.Height = 10;
             Rtg_LB.X = 0; Rtg_LB.Y = e.ClipRectangle.Height - 11; Rtg_LB.Width = 10; Rtg_LB.Height = 10;
             Rtg_RB.X = e.ClipRectangle.Width - 11; Rtg_RB.Y = e.ClipRectangle.Height - 11; Rtg_RB.Width = 10; Rtg_RB.Height = 10;
  
             Color color = Color.FromArgb(51, 94, 168);
             Pen Pen_AL = new Pen(color, 1);
             Pen_AL.Color = color;
             Brush brush = new HatchBrush(HatchStyle.Divot, color);
  
             e.Graphics.DrawString(groupBox1.Text, groupBox1.Font, brush, 6, 0);
             e.Graphics.DrawArc(Pen_AL, Rtg_LT, 180, 90);
             e.Graphics.DrawArc(Pen_AL, Rtg_RT, 270, 90);
             e.Graphics.DrawArc(Pen_AL, Rtg_LB, 90, 90);
             e.Graphics.DrawArc(Pen_AL, Rtg_RB, 0, 90);
             e.Graphics.DrawLine(Pen_AL, 5, 7, 6, 7);
             e.Graphics.DrawLine(Pen_AL, e.Graphics.MeasureString(groupBox1.Text, groupBox1.Font).Width + 3, 7, e.ClipRectangle.Width - 7, 7);
             e.Graphics.DrawLine(Pen_AL, 0, 13, 0, e.ClipRectangle.Height - 7);
             e.Graphics.DrawLine(Pen_AL, 6, e.ClipRectangle.Height - 1, e.ClipRectangle.Width - 7, e.ClipRectangle.Height - 1);
             e.Graphics.DrawLine(Pen_AL, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 7, e.ClipRectangle.Width - 1, 13);
         }
     }
}
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM