WinForms `TabControl` 內建邊距 (Padding) 約 4-6 像素,導致子頁面 (TabPage) 內容無法貼邊顯示,影響全螢幕編輯器、圖表、地圖等需滿鋪的場景。
using System.Windows.Forms;
using System.Drawing;
///
/// 移除 TabControl 內建邊距,讓 TabPage 內容貼邊顯示
///
public class FullTabControl : TabControl
{
public FullTabControl()
{
// 可選:設定預設樣式
this.Padding = new Point(0, 0); // 某些情況下有效
}
///
/// 核心:擴大顯示矩形,抵消內建 Padding
///
public override Rectangle DisplayRectangle
{
get
{
Rectangle rect = base.DisplayRectangle;
// 向四方向各擴展 4px (視版本/主題微調)
return new Rectangle(
rect.Left - 4,
rect.Top - 4,
rect.Width + 8,
rect.Height + 7 // 底部可能需更多
);
}
}
}
使用方式:工具箱右鍵「選擇項目」→ 瀏覽編譯後 DLL → 拖曳 `FullTabControl` 替換原 `TabControl`。或在代碼中動態建立。
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class FullTabControlNative : NativeWindow
{
private const int TCM_FIRST = 0x1300;
private const int TCM_ADJUSTRECT = TCM_FIRST + 40; // 0x1328
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
private TabControl _tabControl;
public FullTabControlNative(TabControl tabControl)
{
_tabControl = tabControl;
AssignHandle(tabControl.Handle); // 子類別化
}
protected override void WndProc(ref Message m)
{
if (m.Msg == TCM_ADJUSTRECT)
{
// 取得 RECT 結構
RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
// 修正邊距:左/上 -4,右/下 +3 (視需求調整)
rc.Left -= 4;
rc.Top -= 4;
rc.Right += 3;
rc.Bottom += 3;
// 寫回
Marshal.StructureToPtr(rc, m.LParam, false);
m.Result = (IntPtr)1; // 表示已處理
return;
}
base.WndProc(ref m);
}
// 釋放時解除子類別化
public void Release() => ReleaseHandle();
}
使用方式:在 Form Load 時實例化:
private FullTabControlNative _tabFixer;
private void Form1_Load(object sender, EventArgs e)
{
_tabFixer = new FullTabControlNative(this.tabControl1);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_tabFixer?.Release();
base.OnFormClosing(e);
}
| 維度 | 方案一:繼承重寫 DisplayRectangle | 方案二:NativeWindow WndProc |
|---|---|---|
| 實作複雜度 | 極低 (單一類別、單一方法) | 中等 (P/Invoke、子類別化、訊息循環) |
| 適用範圍 | 標準 TabControl、設計時支援 | 所有 TabControl、第三方控制項、動態建立 |
| 視覺效果 | 可能影響標籤頁標題區域渲染 | 僅影響客戶區,標籤頁標題不受影響 |
| 維護性 | 高 | 需注意 Handle 重建 (RecreateHandle) 時重新指派 |
| 推薦指數 | ⭐⭐⭐⭐⭐ (一般專案首選) | ⭐⭐⭐⭐ (特殊需求、第三方控制項) |
<!-- WPF TabControl 無邊距 -->
<TabControl>
<TabControl.Resources>
<Style TargetType="TabPanel">
<Setter Property="Margin" Value="0"/>
</Style>
<Style TargetType="TabItem">
<Setter Property="Padding" Value="0"/>
<Setter Property="Margin" Value="0"/>
</Style>
</TabControl.Resources>
<TabItem Header="Page1"><ContentControl Content="{Binding}" /></TabItem>
</TabControl>
WinForms TabControl 邊距問題歷久不衰,方案一「繼承重寫 DisplayRectangle」以最小代碼解決 95% 場景,方案二「WndProc 子類別化」處理棘手兼容性案例。選對工具,告別手動設定 Padding 的痛苦。