Résoudre les problèmes visuels des composants imbriqués en Delphi avec Custom Refresh

Certaines applications Delphi empilent tellement de fenêtres et de frames façon poupées russes qu’au lancement, l’affichage rend les armes à moitié.

Prenez une fiche avec 3 TFrame, contenant chacun un TPageControl, qui embarque ses TTabSheet, où se cache encore un TFrame rempli de composants métier. Vous voulez poser le focus sur un TEdit tout au fond ou sélectionner une valeur dans un TComboBox… et à l’arrivée, la moitié des contrôles jouent à cache-cache. Il faut passer la souris dessus, ou minimiser puis restaurer la fenêtre pour que Windows daigne tout dessiner.

Le coupable ? L’ordre de création des composants imbriqués et l’assignation de leurs handles : tant que Windows n’a pas tous les handles prêts au bon moment, le rendu peut rester incomplet.

Le remède : un message maison

Un petit PostMessage envoyé dans la file Windows suffit à déclencher un rafraîchissement propre, une fois tout le monde en place :

const
  CUSTOM_REFRESH = WM_USER + $9999;

// Pour déclencher le rafraîchissement :
PostMessage(Self.Handle, CUSTOM_REFRESH, WPARAM(LWinControl), 0);

Côté fiche (TForm ou tout TWinControl), on intercepte le message de façon classique :

// Déclaration dans la fiche
procedure HandleMsgCustomRefresh(var Message: TMessage); message CUSTOM_REFRESH;

// Implémentation
procedure TFormExample.HandleMsgCustomRefresh(var Message: TMessage);
begin
  CustomRefreshWinControl(TWinControl(Message.WParam));
end;

Le rafraîchissement récursif

Reste à forcer le redessin du contrôle ciblé et de tous ses enfants via l’API Windows :

procedure CustomRefreshWinControl(AWinControl: TWinControl);
var
  i: Integer;
  Control: TControl;
  WinControl: TWinControl;
  SourceControl, ChildControl, AncestorControl, ChildAncestor: THandle;
begin
  SourceControl := AWinControl.Handle;

  if not IsWindow(SourceControl) then
    Exit;

  i := 0;
  while (not AWinControl.Showing) and (i < 20) do
  begin
    Inc(i);
    Application.ProcessMessages;
  end;

  if not AWinControl.Showing then
    Exit;

  if (csDestroying in AWinControl.ComponentState) then
    Exit;

  if AWinControl.Parent = nil then
    Exit;

  if not AWinControl.Visible then
    Exit;

  InvalidateRect(SourceControl, nil, True);
  UpdateWindow(SourceControl);

  for i := 0 to AWinControl.ControlCount - 1 do
  begin
    Control := AWinControl.Controls[i];
    if Control is TWinControl then
    begin
      WinControl := TWinControl(Control);
      CustomRefreshWinControl(WinControl);
      ChildControl := WinControl.Handle;
      if (WinControl.HandleAllocated) and (IsWindow(ChildControl)) and (GetParent(ChildControl) <> 0) then
      begin
        ChildAncestor := 0;
        try
          AncestorControl := GetAncestor(ChildControl, GA_PARENT);
          if (AncestorControl <> GetDesktopWindow()) then
            ChildAncestor := AncestorControl;
        except
        end;
        if (ChildAncestor <> 0) then
        begin
          InvalidateRect(ChildControl, nil, True);
          UpdateWindow(ChildControl);
        end;
      end;
    end;
  end;
end;

Le duo gagnant, c’est InvalidateRect + UpdateWindow. Avant de les appeler, on vérifie que le contrôle est bien prêt : HandleAllocated, fenêtre valide, visible (ou en cours d’affichage) et surtout pas en pleine destruction (csDestroying). L’appel récursif s’occupe ensuite de passer un coup de pinceau sur chaque enfant.

Résultat : vos contrôles s’affichent enfin tels que vous les avez dessinés en mode conception — sans avoir à secouer la fenêtre pour les réveiller.

Rechercher

Rubriques
Archives
Par mois
Par année