Delphi调用BPL并显示窗体

bpl

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    Label1: TLabel;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
begin
  ShowMessage('BPL包中的消息');
end;

initialization
//注册类
RegisterClass(TForm2);

finalization
//取消注册类
UnRegisterClass(TForm2);

end.

主程序

procedure TForm1.Button1Click(Sender: TObject);
var
  BPLFileName: string;
  PackageHandle: HMODULE;
  FormClass: TFormClass;
  FormInstance: TForm;
begin
  BPLFileName := ExtractFilePath(Application.ExeName) + 'Package1.bpl';
  PackageHandle := LoadPackage(BPLFileName);
  if PackageHandle <> 0 then
  begin
    FormClass := TFormClass(GetClass('TForm2'));
    if Assigned(FormClass) then
    begin
      FormInstance := FormClass.Create(Application);
      try
        FormInstance.ShowModal;
      finally
        FormInstance.Free;
      end;
    end
    else
      ShowMessage('Failed to find form class in BPL');

    UnloadPackage(PackageHandle);
  end
  else
    ShowMessage('Failed to load BPL package');
end;

 需要注意程序中需要勾选Link with runtime packages不然FormClass会等于nil

posted @ 2024-02-28 15:06  liessay  阅读(210)  评论(0编辑  收藏  举报