Mega Code Archive

 
Categories / Delphi / Ide Indy
 

How do I write a simple Delphi Component

Title: How do I write a simple Delphi Component? I would like to write a component that is like a TButton but keeps a count of the number of times it has been clicked. If you've not tried writing a component before then this would be a simple example to begin with. Call your new component TNewButton. TNewButton will be identical to TButton but with some extra code. We can inherit all the behaviour of TButton and add our own extra code to count the clicks. type TNewButton = class(TButton) private public end; The above code would create a class TNewButton which was identical to TButton. Now to add our new functionality. First, we want a private variable to keep count of the number of clicks. By convention, private variables begin with the letter 'f'. It is also good practice to access private variables by using properties. type TNewButton = class(TButton) private fSingleClickCount: integer; public property SingleClickCount: integer read fSingleClickCount write fSingleClickCount; end; Now we need to replace the OnClick event handler with one of our own which will count the clicks. Obviously we want this event handler to also do everything that the TButton OnClick event handler does so we ask it to inherit the TButton OnClick code. type TNewButton = class(TButton) private fSingleClickCount: integer; public procedure Click; override; property SingleClickCount: integer read fSingleClickCount write fSingleClickCount; end; The actual event handler looks like this: procedure TNewButton.Click; begin inc ( fSingleClickCount ); inherited Click; end; Finally we need to register the component with Delphi so that it appears in the component palette. I've chosen to put it in the Samples tab. unit uNewButton; interface uses StdCtrls, Classes; type TNewButton = class(TButton) private fSingleClickCount: integer; public procedure Click; override; property SingleClickCount: integer read fSingleClickCount write fSingleClickCount; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TNewButton]); end; procedure TNewButton.Click; begin inc ( fSingleClickCount ); inherited Click; end; end. Save this file. I've called it uNewButton.pas and install the component by clicking on Delphi's Component | Install Component... menu item. You should now be able to create an application that uses the TNewButton component. If you want to know the number of times your NewButton has been clicked you access the SingleClickCount property e.g. ShowMessage ( IntToStr(NewButton1.SingleClickCount) ); This is a rather simple explanation of a simple component but it might get you started on developing components which I find a fun and rewarding activity. The ability to create one's own components relatively simply is one of the great strengths of Delphi.