1. Home
  2. Computing & Technology
  3. Delphi Programming

Delphi: Incompatible type: 'method pointer and regular procedure' - explained

By Zarko Gajic, About.com

When you are creating components at run time, and want to assign a procedure to an event handler of a component, like in the following code:
procedure ButtonClick(Sender:TObject) ;
begin
//whatever
end;

procedure SomeProcedure...
var aButton:TButton;
begin
   aButton := TButton.Create(nil) ;
   aButton.OnClick = ButtonClick
...
end;

You will get the next error:
Incompatible type: 'method pointer and regular procedure'.

The problem is that a method pointer (OnClick) needs to be a procedure of an object (like TForm), not a regular procedure.

One way around is to create an object to define the procedure. You can start by creating a dummy class...

interface

type
   TEventHandlers = class // create a dummy class
       procedure ButtonClick(Sender: TObject) ;
   end;

...

var EvHandler:TEventHandlers;

implementation

procedure TEventHandlers.ButtonClick(Sender: TObject) ;
begin
   // your code here
end;

...
procedure SomeProcedure...
var aButton:TButton;
begin
   aButton := TButton.Create(nil) ;
   aButton.OnClick = ButtonClick;
...
end;

This compiles!
}

~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Match column title alignments with field alignments in DBGrid
« How to shuffle (randomize position) array values

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2003 Delphi Tips
  7. Delphi: Incompatible type: 'method pointer and regular procedure' - explained

©2009 About.com, a part of The New York Times Company.

All rights reserved.