首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

C# WinForms 非矩形視窗與自訂外形控件實作完整指南

     編輯:Java 相關知識

非矩形視窗實作

WinForms 透過 TransparencyKey 與 BackgroundImage 實現異形視窗:

  1. 準備位圖:繪製非矩形區域(前景色)+ 背景色(將透明)
  2. Form 設定:
    • FormBorderStyle = None(移除標題列)
    • BackgroundImage = 你的位圖
    • TransparencyKey = 背景色(如藍色)
  3. 補回標題列功能:自訂關閉按鈕 this.Close()、拖曳移動視窗(ReleaseCapture() + SendMessage(WM_NCLBUTTONDOWN, HTCAPTION))

自訂外形控件

控件無 TransparencyKey,改用 GraphicsPath 定義區域:

private void CustomButton_Paint(object sender, PaintEventArgs e) {
    GraphicsPath path = new GraphicsPath();
    path.AddString("Click Me!", new FontFamily("Arial"), (int)FontStyle.Bold, 35, new PointF(0,0), StringFormat.GenericDefault);
    CustomButton.Region = new Region(path);
}
  • GraphicsPath:幾何路徑集合(直線、曲線、文字)
  • Region:控件可見/可點擊區域
  • 文字、圓形、多邊形任意外形皆可

GDI+ 核心技術速查

繪圖面取得

// Load 事件
Graphics g = pictureBox.CreateGraphics();
// Paint 事件
Graphics g = e.Graphics;
// OnPaint 覆寫
protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawRectangle(...); }

文字繪製三大類

  • FontFamily:字體家族(如 Arial、微軟正黑體)
  • Font:具體字型(大小、粗體、斜體)
  • StringFormat:對齊、行距、垂直排版

GraphicsPath 進階

GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(20,20,300,200);
gp.AddPie(50,100,300,100,45,200);
gp.AddRectangle(new Rectangle(100,30,100,80));
g.DrawPath(Pens.Blue, gp);
g.FillPath(Brushes.GreenYellow, gp);

Region 與漸層筆刷

// 線性漸層
LinearGradientBrush lgb = new LinearGradientBrush(new Point(0,10), new Point(150,10), Color.Red, Color.Green);
g.FillRectangle(lgb, 10,150,370,30);

// 路徑漸層
GraphicsPath gp = new GraphicsPath(); gp.AddEllipse(10,10,200,100);
PathGradientBrush pgb = new PathGradientBrush(gp);
ColorBlend blend = new ColorBlend();
blend.Colors = new[] {Color.Red, Color.Gray, Color.Green, Color.Blue};
blend.Positions = new[] {0.0f, 0.3f, 0.6f, 1.0f};
pgb.InterpolationColors = blend;
g.FillRectangle(pgb, 0,0,210,110);

座標轉換

g.TranslateTransform(dx, dy);   // 平移
g.RotateTransform(angle);         // 旋轉
g.ScaleTransform(sx, sy);         // 縮放
// 全域轉換影響所有後續繪製
// 局部轉換:GraphicsPath.Transform(matrix)

Alpha 混色與抗鋸齒

// Alpha:Color.FromArgb(alpha, r, g, b)  0=全透明 255=不透明
// 抗鋸齒
g.SmoothingMode = SmoothingMode.AntiAlias;

實戰提醒

  • TransparencyKey 顏色不可與前景重疊,否則前景會變透明
  • 異形視窗在多螢幕、不同 DPI 下需實測相容性
  • Graphics、Brush、Pen、GraphicsPath 用畢須 Dispose() 或 using 釋放非託管資源
  • 大量繪製建議雙緩衝:this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved