1. 程式人生 > >Windows中按鈕文字的佈局樣式

Windows中按鈕文字的佈局樣式

用到CheckBox的按鈕居右處理,發現竟然沒有文字居右的選項。從面向物件的角度來說,咱要過載掉CreateParams重新建立一個新類,可是這個功能基本上很少用到啊,那麼就只能用Windows Api 函式直接修改啦。上程式碼:

function SetWinControlTextAlignment(const AControl: TWinControl; const Alignment: TAlignment = taLeftJustify): Boolean;
var
  AStyle: Integer;
begin
  Result := False;

  if not Assigned(AControl) then
    Exit;

  AStyle := GetWindowLong(AControl.Handle, GWL_STYLE);

  case Alignment of
    taLeftJustify: AStyle := AStyle or BS_LEFT;
    taRightJustify: AStyle := AStyle or BS_RIGHT;
    taCenter: AStyle := AStyle or BS_CENTER;
  end;
  SetWindowLong(AControl.Handle, GWL_STYLE, AStyle);

  AControl.Invalidate;

  Result := True;
end;

function SetWinControlTextLayout(const AControl: TWinControl; const TextLayout: TTextLayout = tlTop): Boolean;
var
  AStyle: Integer;
begin
  Result := False;

  if not Assigned(AControl) then
    Exit;

  AStyle := GetWindowLong(AControl.Handle, GWL_STYLE);

  case TextLayout of
    tlTop: AStyle := AStyle or BS_TOP;
    tlCenter: AStyle := AStyle or BS_CENTER;
    tlBottom: AStyle := AStyle or BS_BOTTOM;
  end;
  SetWindowLong(AControl.Handle, GWL_STYLE, AStyle);

  AControl.Invalidate;

  Result := True;
end;

注意:這兩個函式只對Button類有效(Button,CheckBox,RadioButton),別的應該無效的。另外,沒有什麼嚴格測試,自己將就著用用吧。