FireMonkey Form in a dll, loaded from a VCL Application

两盒软妹~` 提交于 2019-12-02 01:59:21

This answer applies to Delphi XE2 Update 2, I don't know if things have changed with Update 3.

I started the Embarcadero thread. Starting up GDI+ from the host application isn't an option for me. So far everything is working from the DLL side without errors but nothing has been released to the outside world yet either.

If you are able to modify your C host application, you may find the MSDN GdiplusStartup() documentation useful.

====

Using FireMonkey In a DLL Without Starting GDI+ In Host Application

Add this unit to your project:

unit InitFmxHack;

interface

procedure InitGDIP; // Call before using FMX.
procedure FreeGDIP; // Call after using FMX.

// NOTE:
// InitGDIP() must be called before instantiating a FireMonkey form.
// FreeGDIP() must be called after all FireMonkey forms are destroyed.
//
// InitGDIP/FreeGDIP can not be called from the initalization or finalization sections,
// or any method called from these sections.
//


implementation

uses
  System.SysUtils,
  Winapi.GDIPAPI,
  Winapi.GDIPOBJ,
  FMX.Types;

var
  NeedToShutdownGDIPlus: Boolean;
  GDIPlusInput: TGDIPlusStartupInput;
  gdiplusToken: Cardinal;
  TempRgn: GpRegion;

type
  TBitmapAccess = class(TBitmap);

procedure InitGDIP;
begin
  NeedToShutdownGDIPlus := False;
  case GdipCreateRegion(TempRgn) of
    Ok: GdipDeleteRegion(TempRgn);
    GdiplusNotInitialized:
    begin
      GDIPlusInput.GdiplusVersion := 1;
      GDIPlusInput.DebugEventCallback := nil;
      GDIPlusInput.SuppressBackgroundThread := False;
      GDIPlusInput.SuppressExternalCodecs := False;
      GdiplusStartup(GDIPlusToken, @GDIPlusInput, nil);
      NeedToShutdownGDIPlus := True;
    end;
  end;

end;

procedure FreeGDIP;
begin
  // HACK: Need to forcibly release a GDI+ object held in a global variable.
  FreeAndNil(TBitmapAccess(GetMeasureBitmap).FCanvas);

  // These lines have been copied from Winapi.GDIPOBJ. I'm not 100% sure
  // if there needed but it's probably safer to include them as they are part of
  // the standard FireMonkey shutdown sequence. Similar code is also found in
  // the VGScene library.
  if Assigned(GenericSansSerifFontFamily)           then FreeAndNil(GenericSansSerifFontFamily);
  if Assigned(GenericSerifFontFamily)               then FreeAndNil(GenericSerifFontFamily);
  if Assigned(GenericMonospaceFontFamily)           then FreeAndNil(GenericMonospaceFontFamily);
  if Assigned(GenericTypographicStringFormatBuffer) then FreeAndNil(GenericTypographicStringFormatBuffer);
  if Assigned(GenericDefaultStringFormatBuffer)     then FreeAndNil(GenericDefaultStringFormatBuffer);

  // Finalise GDI+ here if needed...
  if NeedToShutdownGDIPlus then GdiplusShutdown(GDIPlusToken);
end;

end.

To use:

InitFmxHack.InitGDIP;

// 1. Create form here.
// 2. Use form.
// 3. Destroy form. 

InitFmxHack.FreeGDIP;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!