Archive

Posts Tagged ‘usefull’

How to Create Control Arrays

December 15th, 1999 m3Rlin No comments

Visual Basic allows programmers to create control arrays. If VB does, then how about Delphi? It sure does, but the whole idea is a bit different than in Visual Basic. You can do this to allow all controls to share a message handler (e.g. all the components can have an <i>OnClick</i> handler). For example, let’s create an array of 10 <i>TButton</i> controls:
<pre>
<b>type</b>
TForm1: <b>class</b>(Form);

Button1: TButton;
Button2: TButton;

Button10: TButton;
<b>procedure</b> FormCreate(Sender: TObject);
<b>public</b> <i>// Or “private” if you won’t use it outside this class</i>

aButtons: <b>array</b>[1..10] <b>of</b> TButton; <i>// In Delphi 4+ you can create dynamic arrays</i>

<b>end</b>;

<b>implementation</b>

<i>// In this example the array is created on program startup but it can be created anywhere</i>
<b>procedure</b> TForm1.FormCreate(Sender: TObject);
<b>begin</b>
<i>// Create the array</i>
aButtons[1] := Button1;
aButtons[2] := Button2;

aButtons[10] := Button10;
<b>end</b>;
</pre>
Now some examples on how to access the buttons:
<pre>
aButtons[1].Caption := ‘The first button’;

<i>// This code can be very usefull when a group of components has to resize when it’s parent resizes</i>
aButtons[1].Width := Form1.Width – 100;
</pre>
…and the idea on how to assign the same event handler for the controls in the array:
<pre>
<b>var</b>
iI: Integer;

<b>for</b> iI := 1 <b>to</b> 10 <b>do</b>
aButtons[iI].OnClick := FormOnClick;
</pre>
You don’t have to group components of one type. You can create an array of <i>TControl</i> or <i>TComponent</i>. All you have to do is type cast the controls when initializing the array.

How to Make a Desktop Screenshot

December 15th, 1999 m3Rlin No comments

Making screenshots is actually easier than you may have assumed. This tip makes screenshots of the desktop only, but you can implement it to your needs. A lot of people have asked me how to get an image of the screen. For various reasons :-) I think this is a very usefull idea so I decide to include it in my FAQ. Here is the function that captures the desktop and returns it as a TBitmap:

function GetDesktopImage: TBitmap;
var
  hdcDesktop: HDC;
begin
  Result := TBitmap.Create;
  hdgcDesktop := GetDC(0);
  try
    try
      with Result do begin
        PixelFormat := pf32ibt;
        Height := Screen.Height;
        Width := Screen.Width;
        BitBlt(Canvas.Handle, 0, 0, Width, Height, Desktop, 0, 0, SRCCOPY);
        Modified := True;
      end;
    finally
      ReleaseDC(0, Desktop);
    end;
  except
    Result.Free;
    Result := nil;
  end;
end;