Thursday, July 21, 2011

Read mouse pointer aka cursor position in Delphi!

Well this seems to a problem sometimes when someone asks us how to find where my cursor is currently located. Well why to say when we can infact show where actually is our mouse cursor at given point in time. To do this we will create a simple Delphi program as follows -

program Project1;
{$APPTYPE CONSOLE}
uses
  SysUtils, Controls, Windows;
var
  MyMouse : TMouse;
begin
  MyMouse := TMouse.Create;
  While True do
  begin
    WriteLn('(X, y) = (' + inttostr(TPoint(MyMouse.CursorPos).x) + ',' + inttostr(TPoint(MyMouse.CursorPos).y) + ')');
    sleep(300);
  end
end.

As we can see we create a simple Mouse cursor for ourselves in this small program and simply place it in a while loop of 300 ms to trace the current position of mouse cursor in our screen.

Simple isn't it?

Limit of Recursion!

Recently I was going through Linked in Delphi user's group and found that few programming sections in a programming site needs examples in Delphi to demonstrate the methodology of implementing solution to a problem in various languages. On visiting the site I found that there is a need of particular example to find - Limit of Recursion as implemented in the language. This is a very interesting question as we all use recursion for implementing various solutions but we rarely care to find the actual limit to which we can implement recursion. Although most of this problems answer depends on the memory available to particular systems however we still can check this limit by implementing a very basic recursive function.

The idea behind this simple program is to keep on iterating and visit nest level for a recursive function till the time we go out of memory. So the limiting condition here is the draining of the memory. A simple program like the following will demonstrate this limit -


unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Level : integer;
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

function Recursive(Level : integer) : integer;
begin
try
Level := Level + 1;
Recursive(Level);
except on e: Exception do
Result := Level;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Level = ' + inttostr(Level));
ShowMessage('Level = ' + inttostr(Recursive(Level)));
end;

end.

This program takes up an integer value and tries to increment the value and call the function till StackOverflow error occurs and then simply prints this value. This implementation gave the following result on my Windows Vista 64 bit computer for integer value - 4375221. The values can differ if we take int64 instead of signed integer in the above example.

Recursion in Delphi!

Recursion is a very generically used term in computer programming. Some problem in computer programming which allow repetition of some particular task again and again with some terminating check can be implemented very easily with the help of the concept of recursion.

A simplest example is to find the factorial of 5. The result is derived as -

5! = 5 X 4 X 3 X 2 X 1
5! = 120

This simple program can be easily designed using recursion or using recursive calls to the same function again and  again. e.g. -

fact() = fact(i) X fact(i - 1)

The above expression at each step calls the factorial function again with one value less for variable i in each call.

A simple Delphi program to demonstrate the recursion concept in Delphi is as follows -

A button click is used to trigger the recursive function -

procedure TForm1.Button1Click(Sender: TObject);
var
    a : integer;
begin
    a := fact(5);
    ShowMessage(inttostr(a));
end;

and the simple recursive function is -

function fact(i : integer) : integer;

begin
    if (i = 1) then
    begin
        fact := 1;
    end
    else
    begin
        fact := i * fact(i - 1);
    end;
end;
As we can see in the above example fact function calls itself till the value of i variable reaches 1 which is the terminating condition for our recursive function and no further recursions are made.

The result returned for above example is 120.

Saturday, October 23, 2010

Does multiple inheritance exists in Delphi?

Sometimes it is asked - Delphi supports multiple inheritance or not?

and the answer which usually comes out is - Yes via interfaces, but the problem here is can we really say that implementing an interface actually achieves multiple inheritance in real sense or is it something else. Well the answer to this confusion is that 'No' we cannot say that implementing an interface is a way to achieve multiple inheritance because the first promise that multiple inheritance or inheritance in itself wants is that not only the declaration but also some of the behaviour should get inherited by the child class from the parent class/classes else just by suggesting a declaration of what should be achieved by a child class can never be inheritance. It is as simple as considering the analogy a child inherits some features from both mother and father but its never that a implementation is not inherited from any of the two.

Using interfaces is simply a way of allowing a boundation to the inheriting class to implement certain features so that it meets certain criteria nothing more than that. So the only language to implement multiple inheritance successfully in its real sense is C++ as of now and as per my knowledge. Delphi goes the way Java or C# tried to achieve the similar functionality via interfaces.

Difference between Method pointers and procedural pointers

While I was having some talk with my friends we ended up into a confusion as what exactly is the difference between the method pointers and procedureal pointers in Delphi and how it can be understood well. Well for a seasoned professional may be the answer to it is quiet easy but it took sometime before we really hit on the answer.

Method pointers are basically pointers to a method which is related to a class and as it is related to a class hence Delphi does pass on the 'Self' implicitly to the method so that the object can be referred to within the method pointed to by the method pointer. In case of a procedural pointer this 'Self' is what is missing and hence we can't have a procedural pointer refer to a class method.

This could be easily remembered the way a class method is defined -

MyClass.MyProcedure;

In this was we can see that we actually have MyClass which suggests that MyProcedure belongs to it. A normal procedure would be defined in this way -

MyProcedure;

suggesting that there is no class to which it belongs and hence no 'Self'.

Sunday, June 20, 2010

Is Application Object a window in Delphi?

Often sometimes while working in Delphi I wondered whether the Application object itself is a window or not.. and if so then where exactly is this window and why is it not visible? Going through Marco Cantu's Mastering Delphi book I found that yes infact Application object in delphi is infact a window but than this fact drove me into curiosity to just see this window visibly and hence I thought of programming a bit on this fact. Though Marco suggested that the best way to see that "Application object is infact a window" is to run Delphi, select "New Application" which creates a new windows application and gives Form1 as a default form and then simply press the Run button. Now on looking into the task bar we are see that the title for our new application is getting displayed as Project1 and not Form1 which clearly suggests that there is infact a hidden window in our newly created windows application. This hidden window is none other than very own Application window but still if we could see the window well stretched on our desktop then it would be a better confirmation to this fact after all to see it clearly is better than mearly realising a fact... Am I Correct? So here we go..

Now to start with - first here is a bit of delphi lecture - If we will look at how TApplication has been defined in Delphi then we find that the class has been inherited from TComponent class but than on going through the class definition we find that Application object infact allows programmer to have access to its handle value.. Handle in itself is a unique 32bit (for 32 bit systems) number that windows OS assigns to each window that will be handling any sort of windows messaging.
Once while I was going through some VC++ lessons and VB programming I once read that if we have access to the handle value fo a window we can manipulate that window to the maximum extent via the windows API's and hence I plan here to do the same to make the "Application Object" show its coordinates and make itself visible...

Monday, January 11, 2010

A list of popular applications created in Delphi!

Hi All,

I was going through a lot of discussions in forums and other communities when the discussion turned towards the facts as how many and which popular applications have been created using the Delphi and the answer most were giving was - Skype. Though Skype is indeed a very popular product and ofcourse distributed under Freeware software category however it is not the only product that is popular and has been developed using Delphi. I went through various sites and found a list of such applications created using Delphi. Instead of presenting the same list again at this place here is the link to one such page - http://delphi.wikia.com/wiki/Good_Quality_Applications_Built_With_Delphi
I hope there will be many more such applications that would have been created using this excellent tool but for now above is the list.

Thursday, May 14, 2009

Initialization and Finalization Sections of a Unit!

"Initialization & Finalization Sections - What are they?" - Ever heard of these names earlier while programming delphi application, must have but never bothered much about them.. Guess Right??..

Yes, these two terms are the optional sections of a delphi unit, the common one being the unit header, interface section and implementaion section. However, sometimes we are in a need to perform certain tasks before any of the units code is executed, it is then that we start searching for these two optional sections.

Wheneever we need to do some extra work before any other code is read we place that piece of code in the Initialization section of the unit which is then being called while the application is executed. Now, once this is done and the application needs to terminate then all the resources allocated during the Initialization section of a unit are done free in the finalization section. These two are being declared like this -

unit

interface

implementation

initialization
{Place initialization code here}
finalization
{Place finalization code here}
end.

i.e. before the final end of the unit.

Sunday, April 20, 2008

Introduction to Dynamic Link Libraries DLLs.

Once there was a discussion between me and my friend as why DLL's are required and how to do that in Delphi. So, I thought of demonstrating a very simple program to show how simple it is to create a DLL in delphi.

Dynamic link library or DLL is a collection of routines (i.e. small programs) that can be called by other applications and DLLs.

Dynamic link libraries or DLLs are pieces of sharable codes that various other applications can use. These DLLs contain common code that may be required by different applications to perform similar operations. Thus allowing a single copy of routines to be used by many applications at the same time.

Another advantage of DLLs is that we can safely use routines created in other development environments like VB, C++ to be used in delphi or vice-versa.

Now you must be thinking as how to create a DLL in delphi. Is it really difficult or is it simple?

Well dear developer no need to worry. Its pretty simple in delphi.

Here I will try to create a simple delphi application using a new DLL -
This example will try to do the following for us -

First we will create a DLL that will have methods in it -

  • First will be a procedure and will display a welcome message.
  • Second procedure will display a message dialog and will tell us when summation of numbers will start.
  • Third procedure will also display a message dialog and will tell us when the summation is over and finally,
  • Fourth will be a function and will actually do summation of two numbers for us and return the result back to our calling program.
The two methods "Welcome" and "sumnumbers" will be called by our delphi application, remaining two are called from inside the sumnumbers function and are for our dll's internal use.

So all set in our mind then lets create our DLL now ->

First open Delphi and select File -> New -> DLL to create a DLL template for us. Then add Dialogs unit to uses portion of the DLL in case it is not already present (This is because I want to show a dialog box in our DLL to highlight the progress). Now, Save the project as MyLibrary.

Well thats not all done, we have to do some more...

Sunday, April 13, 2008

Can Objects be assigned to a TStringList?

Well if someone asks that can we store an object in a TStringlist or should we use only TList for this purpose, the answer should be ----> Yes ofcourse!.

Now how to do that and where can I use such facility. Now first to answer why should we require this feature if at all. One place where we can use such a feature is when we are required to save or associate an object to a particular name, like saving a location name with the corresponding bitmap.

Now coming to how to do that in delphi. The answer is using the Objects property associated with TStringlist. Delphi gives the power of associating objects to tstringlist using this simple property.


Please see the below example to see how to do that -

Here in this example add a button to a simple delphi form. Now add two edit texts and add a TMemo component. Now write the following code on the button click event -

procedure TForm1.Button2Click(Sender: TObject);
var
mystringlist : tstringlist;
begin
Memo1.clear;
mystringlist := tstringlist.create();
mystringlist.Add(edit1.text);
mystringlist.Objects[0] := edit1;
mystringlist.Add(edit2.text);
mystringlist.objects[1] := edit2;
memo1.Lines.Add(TEdit(mystringlist.objects[0]).name);
memo1.Lines.Add(TEdit(mystringlist.objects[1]).name);
end;

Run the delphi program by pressing F9 key or navigating to "Run" Menu and clicking on "Run" Menu item.

Now click on the button on the form and you will see that memo displays two strings edit1 and edit2. Here the names have been derieved from the objects stored in the stringlist.

This was just a demonstration program and the power of such a feature can be easily utilized in performing complex tasks.