VCL-Style Issues in DLL

The reason of the access violation is that, vcl styles in Delphi XE2 does not seem to be designed with VCL styles in a dll in mind. The AV is thrown in the WM_SIZE handler of the form style hook:

procedure TFormStyleHook.WMSize(var Message: TWMSize);
begin
  if IsIconic(Handle) and (Application.MainForm.Handle <> Handle) then
    InvalidateNC;

  ...

The style hook tests if the message is being handled on the main form, but there's no main form in a dll. Accessing the handle of the unassigned reference causes the exception.


The below workaround introduces a descendant style hook to prevent this, it bypasses the check for the main form and lets the processing of the message continue at TWinControl.

This is the entire, modified 'unit3' in the dll:

unit Unit3;

interface

uses forms, messages, themes, windows, Unit2;

procedure showfrm;

implementation

type
  TForm2StyleHook = class(TFormStyleHook)
  private
    procedure WMSize(var Message: TWMSIZE); message WM_SIZE;
  end;

procedure TForm2StyleHook.WMSize(var Message: TWMSIZE);
begin
  if IsIconic(Handle) then begin
    // duplicate the code in ascendant, for whatever it serves
    InvalidateNC;
    // the rest of the code in ascendant class is related with MDI

    Handled := False; // if this is set to true TWinControl.WndProc returns
  end else
    inherited;
end;

procedure showfrm;
begin
  TStyleManager.Engine.RegisterStyleHook(TForm2, TForm2StyleHook);

  with TForm2.Create(nil) do
    Show;
end;

end.

Note also the possibility of continuing to hit issues like these while considering to use styles in a dll.