> Home > Coding

General Delphi Tips

Common problems with OnCreate...
 
I am sure you have experienced that, too: You want to do something when the form is created, but all you get is an exception or something. There is a rather simply solution to this: create a const boolean named launched, do that thing OnActivate rather than OnCreate, and set launched to true. Isn't it a fascinating side-effect to see that consts within a procedure remember their last (!) value even when the procedure is called several time?

procedure myform.onactivate (sender:tobject);
const
launched : boolean=false;
begin
if launched=false then begin
launched:=true //and your code, of course
end;
end;

Is Delphi currently running?
 
Something rather easy when you know how to is to find out if a certain program is running - when you know it's Window title. The following function tells if any application with the specified title runs. This way it works only with Delphi written programs!

function running (wcaption: string):boolean;
var ishandle:Hwnd;
const
temp: array[0..12] of char =
'tapplication'#0;
begin
ishandle:=findwindow(temp, pchar(wcaption));
running:=(ishandle<>0)
end;
To find out if Delphi is running, for example, use:
if (running('Delphi')) or (running('Delphi 2.0'))
or (running('Delphi 3.0)) then //your code

Paint anywhere !!!
 
Ever wished to paint in the window of Word, or on the desktop? Have a look at this:

procedure TForm1.Button1Click(Sender: TObject);
var thehandle:thandle;
thecanvas:tcanvas;
begin
thecanvas:=tcanvas.create;
winexec('notepad.exe',sw_normal);
thehandle:=findwindow('notepad',nil);
thecanvas.handle:=getdc(thehandle);
thecanvas.rectangle(0,0,100,100);
thecanvas.free;
end;

For painting the screen itself, use: thecanvas.handle:=createdc('DISPLAY',Nil,Nil,Nil);