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),别的应该无效的。另外,没有什么严格测试,自己将就着用用吧。

猜你喜欢

转载自blog.csdn.net/yayongm/article/details/79753082