在 Delphi 開發中,TListView 控制項預設的標題列具有立體邊框效果。若需實作扁平化(Flat)風格的標題列,可透過 Windows API 修改標題列控制項的視窗樣式。本文將示範如何移除標題列的 3D 邊框,打造現代化扁平介面。
TListView(命名為 ListView1)與一個 TButton(命名為 Button1)。ListView1.ViewStyle 設為 vsReport,並加入幾個欄位以利觀察效果。Button1 的 OnClick 事件中撰寫以下程式碼。uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
procedure TForm1.Button1Click(Sender: TObject);
const
LVM_GETHEADER = $1000 + 31; // 取得標題列控制項控制代碼
var
hHeader: THandle;
Style: DWORD;
begin
// 1. 取得 ListView 內建標題列的視窗控制代碼
hHeader := SendMessage(ListView1.Handle, LVM_GETHEADER, 0, 0);
if hHeader = 0 then Exit;
// 2. 取得目前視窗樣式
Style := GetWindowLong(hHeader, GWL_STYLE);
// 3. 切換 HDS_FLAT 樣式位元(值為 $0002)
// 若原本有 3D 樣式則移除,若無則加上;這裡示範移除 3D 效果
Style := Style xor HDS_FLAT; // HDS_FLAT = $0002,若未定義可直接用 $0002
// 4. 套用新樣式
SetWindowLong(hHeader, GWL_STYLE, Style);
// 5. 強制重繪 ListView 以生效
SetWindowPos(ListView1.Handle, 0, 0, 0, 0, 0,
SWP_NOZORDER or SWP_NOSIZE or SWP_NOMOVE or SWP_DRAWFRAME or SWP_FRAMECHANGED);
end;
HWND。$0002。設定此旗標可移除標題列的立體邊框,呈現扁平外觀。SWP_FRAMECHANGED 旗標通知系統非用戶區已變更,觸發重繪。unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
ListView1: TListView;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
// 初始化 ListView 範例資料
ListView1.ViewStyle := vsReport;
ListView1.Columns.Add.Caption := '姓名';
ListView1.Columns.Add.Caption := '年齡';
ListView1.Columns.Add.Caption := '城市';
with ListView1.Items.Add do
begin
Caption := '張三';
SubItems.Add('25');
SubItems.Add('台北');
end;
with ListView1.Items.Add do
begin
Caption := '李四';
SubItems.Add('30');
SubItems.Add('台中');
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
LVM_GETHEADER = $1000 + 31;
var
hHeader: THandle;
Style: DWORD;
begin
hHeader := SendMessage(ListView1.Handle, LVM_GETHEADER, 0, 0);
if hHeader = 0 then Exit;
Style := GetWindowLong(hHeader, GWL_STYLE);
Style := Style xor $0002; // 切換 HDS_FLAT
SetWindowLong(hHeader, GWL_STYLE, Style);
SetWindowPos(ListView1.Handle, 0, 0, 0, 0, 0,
SWP_NOZORDER or SWP_NOSIZE or SWP_NOMOVE or SWP_DRAWFRAME or SWP_FRAMECHANGED);
end;
end.
點擊按鈕後,ListView 的標題列將瞬間從預設的立體邊框轉變為扁平樣式,適合搭配現代化 UI 設計。
FormCreate 或 ListView1 的 HandleNeeded 事件中。