How to draw on the Windows desktop #198

Need to draw text or graphic on screen?

Here's how to do it:

  1. File -> New -> Application
  2. Put a button anywhere on the form
  3. Double-click the button and Copy / Paste this code
procedure TForm1.Button1Click(Sender: TObject);
const
  (* our text *)
  CTHE_TEXT = 'I Love Delphigeist';
var
  (* we need a canvas object *)
  theCanvas: TCanvas;
begin
  (* create theCanvas *)
  theCanvas := TCanvas.Create;
  (* get Desktop canvas handle *)
  theCanvas.Handle := GetWindowDC(0);
  (* we don't want a rectangle behind our text this is optional you can comment
  next line with "//" and see how it looks *)
  theCanvas.Brush.Style := bsClear;
  (* set the font name *)
  theCanvas.Font.Name := 'Courier New';
  (* we want it bold *)
  theCanvas.Font.Style := [fsBold];
  (* set the size *)
  theCanvas.Font.Size := 60;
  (* lime looks good if your wallpaper has dark colors *)
  theCanvas.Font.Color := clLime;
  (* draw the text *)
  theCanvas.TextOut(50, 50, CTHE_TEXT);
  (* clear allocated memory to our theCanvas object *)
  FreeAndNil(theCanvas);
  (* that's it *)
end;

Now if you want to draw a TBitmap or TJPEGImage on the desktop then replace

  theCanvas.TextOut(50, 50, CTHE_TEXT);

with

  (* create a TBitmap named thisBitmap and load image into it *)
  (* now do the drawing *)
  theCanvas.Draw(50, 50, thisBitmap);

To use a TJPEGImage is similar, just replace thisBitmap with some suitable TJPEGImage variable.

This tip lightly modified by DelphiDabbler.

Author: Dorin Duminica
Contributor: topellina
Added: 2012/09/17
Last updated: 2012/09/17