Des TPanels plus arrondis… mais pas que

Les contrôles VCL d’origine ont des angles aussi accueillants qu’un lundi matin. Un jour, j’ai trouvé comment arrondir ceux d’un TPanel, puis j’en ai fait une méthode générique qui marche aussi sur un TFrame, un TBitBtn, un TMemo, un TGroupBox…

La méthode

CreateRoundRectRgn dessine une région aux coins arrondis (p5 et p6 sont la largeur et la hauteur de l’ellipse des coins : plus c’est grand, plus c’est rond), puis InflateRect ajuste la zone interne pour que le contenu ne soit pas rogné.

procedure RoundCornerOf(Control: TWinControl; p5, p6, dx, dy: Integer) ;
begin
  with Control do
  begin
    var R := ClientRect;
    var rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, p5, p6) ;
    Perform(EM_GETRECT, 0, lParam(@r)) ;
    InflateRect(r, dx, dy) ;
    Perform(EM_SETRECTNP, 0, lParam(@r)) ;
    SetWindowRgn(Handle, rgn, True) ;
    Invalidate;
  end;
end;

À l’essai

Un appel par contrôle, à la création de la fiche (le DFM de test est en bas de l’article) :

procedure TForm1.FormCreate(Sender: TObject);
begin
  RoundCornerOf(Pnl, 20, 20, -4, -4);
  RoundCornerOf(Btn, 10, 10, -2, -2);
  RoundCornerOf(Memo, 5, 5, -1, -1);
  RoundCornerOf(CheckBox, 5, 5, -4, -4);
  RoundCornerOf(GroupBox, 10, 10, -2, -2);
end;

Résultat : des contrôles aux coins nettement plus doux.

Le DFM pour tester

À coller dans une fiche vide pour reproduire l’exemple :

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 437
  ClientWidth = 525
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -12
  Font.Name = 'Segoe UI'
  Font.Style = []
  OnCreate = FormCreate
  TextHeight = 15
  object Pnl: TPanel
    Left = 16
    Top = 32
    Width = 185
    Height = 120
    BevelOuter = bvNone
    Color = clGradientActiveCaption
    ParentBackground = False
    TabOrder = 0
    StyleElements = []
  end
  object Btn: TBitBtn
    Left = 224
    Top = 32
    Width = 75
    Height = 25
    Caption = 'Btn'
    TabOrder = 1
  end
  object Memo: TMemo
    Left = 224
    Top = 63
    Width = 185
    Height = 89
    TabOrder = 2
  end
  object CheckBox: TCheckBox
    Left = 16
    Top = 168
    Width = 97
    Height = 17
    Caption = 'CheckBox'
    TabOrder = 3
  end
  object GroupBox: TGroupBox
    Left = 168
    Top = 168
    Width = 273
    Height = 129
    Caption = 'GroupBox'
    TabOrder = 4
  end
end

Rechercher

Rubriques
Archives
Par mois
Par année