Marco Web Center

[an error occurred while processing this directive]

Home: Code Repository: Mastering Delphi 5

Project DYNACALL

Project Structure


DYNACALL.DPR

program Dynacall;

uses
  Forms,
  DynaForm in 'DynaForm.pas' {Form1};

{$R *.RES}

begin
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

DYNAFORM.PAS

unit DynaForm;

interface

uses
  SysUtils, Windows, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, Spin;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Label1: TLabel;
    SpinEdit1: TSpinEdit;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

type
  TIntFunction = function (I: Integer): Integer; stdcall;

const
  DllName = 'Firstdll.dll';

procedure TForm1.Button1Click(Sender: TObject);
var
  HInst: THandle;
  FPointer: TFarProc;
  MyFunct: TIntFunction;
begin
  HInst := LoadLibrary (DllName);
  if HInst > 0 then
  try
    FPointer := GetProcAddress (HInst,
      PChar (Edit1.Text));
    if FPointer <> nil then
    begin
      MyFunct := TIntFunction (FPointer);
      SpinEdit1.Value := MyFunct (SpinEdit1.Value);
    end
    else
      ShowMessage (Edit1.Text + ' DLL function not found');
  finally
    FreeLibrary (HInst);
  end
  else
    ShowMessage (DllName + ' library not found');
end;

end.

DYNAFORM.DFM

object Form1: TForm1
  Left = 241
  Top = 155
  Width = 368
  Height = 139
  Caption = 'Dynamic DLL Call'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clBlack
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 25
    Top = 20
    Width = 44
    Height = 13
    Caption = '&Function:'
    FocusControl = Edit1
  end
  object Label2: TLabel
    Left = 32
    Top = 72
    Width = 27
    Height = 13
    Caption = '&Value'
    FocusControl = SpinEdit1
  end
  object Button1: TButton
    Left = 239
    Top = 16
    Width = 89
    Height = 23
    Caption = '&Call'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Edit1: TEdit
    Left = 80
    Top = 16
    Width = 145
    Height = 21
    TabOrder = 1
    Text = 'Double'
  end
  object SpinEdit1: TSpinEdit
    Left = 80
    Top = 68
    Width = 146
    Height = 22
    MaxValue = 0
    MinValue = 0
    TabOrder = 2
    Value = 10
  end
end