OnPaint event example for Delphi

1.

Start with the project that you created in Loading and Displaying an Image.

2.

Add the following declarations to the private section of the Unit1 file:

MyRect: TRect; {Used with the OnPaint event example}
MyPoint: TPoint; {Used with the OnPaint event example}

3.

Add a button to the top of your main form, and in the Object Inspector box, change both its name and caption to Toggle.

4.

Add an edit box to the top of your form, and in the Object Inspector box, change its name to Directions, and change its Text property to the following:

Use the Toggle button to turn on or turn off Click-Splat

5.

Code the Toggle button's Click procedure as follows. This code uses the Enabled property to toggle the LEAD control's ability to respond to click events.

procedure TForm1.ToggleClick(Sender: TObject);

begin
Lead1.AutoRepaint := False;
If (Lead1.Enabled = False) Then
begin
  Lead1.Enabled := True;
  Directions.Text := 'Click on the image for a splat';
  Toggle.Caption := 'Disable';
end
Else
begin
  Lead1.Enabled := False;
  Directions.Text := 'Click does nothing';
  Toggle.Caption := 'Enable';
end;

end;

6.

Code the LEAD control's Click procedure as follows. When the Enabled property is true, this code uses a Windows API call to generate a paint event.

procedure TForm1.Lead1Click (Sender: TObject);
var
hCtl: THandle;
begin
{Do not use this event until the user enables it.}
If Toggle.Caption <> 'Disable' Then Exit;

{ Use InvalidateRect to generate a paint message}
MyRect.left := 0;
MyRect.top := 0;
MyRect.bottom := round(Lead1.Height);
MyRect.right := round(Lead1.Width);
hCtl :=.Lead1.handle;
InvalidateRect( hCtl, @MyRect, True);

end;

7.

Code the LEAD control's Paint procedure as follows. The procedure uses Windows GDI functions to draw random lines on the control whenever there is an OnPaint event.

procedure TForm1.Lead1Paint(Sender: TObject);
var
i, xStart, yStart, xDelta, yDelta, xEnd, yEnd: Integer;
LeadClientDC: HDC;

begin
{Do not use this event until the user enables it.}
If Toggle.Caption <> 'Disable' Then Exit;

MyPoint.x := 0;
MyPoint.y := 0;

{ Create a device context for the control that the GDI functions can access}
LeadClientDC := Lead1.GetClientDC;

{ Draw random lines on the control. This is an overlay that does not affect the bitmap.}
xStart := Random(round(Lead1.Width) + 1);
yStart := Random(round(Lead1.Height) + 1);
MoveToEx(LeadClientDC, xStart, yStart, @MyPoint);
For i := 1 To 50 do
Begin
  xDelta := Random(81) - 40;
  yDelta := Random(81) - 40;
  xEnd := xStart + xDelta;
  yEnd := yStart + yDelta;
  LineTo(LeadClientDC, xEnd, yEnd);
  MoveToEx(LeadClientDC, xStart, yStart, @MyPoint);
end;

{ Remove the lock from the device control}
Lead1.ReleaseClientDC;

end;

8.

Run your program to test it.