Saturday, September 12, 2009

How to draw text on Screen

Need to draw text or graphic on screen?
Here's how to do it:
 - File -> New -> Application
 - Put a button anywhere on the form
 - Double-click the button and Copy-Paste this code
procedure TForm1.Button1Click(Sender: TObject);
(* our text *)
const
  CTHE_TEXT = 'I Love Delphigeist';
(* we need a canvas object *)
var
  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 look 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 Desktop then replace
  theCanvas.TextOut(50, 50, CTHE_TEXT);
with
  theCanvas.Draw(50, 50, thisBitmap{or thisJpegImage});
Note
You must initialize the variable first and load an image to it!

2 comments:

  1. In my Chat program (www.magchat.com) I have a special effect that causes bullet holes to be displayed on screen... the trouble is it steals the focus and freezes up the client until it is done... my programmer is displaying a form using code to cause the form to look like the bitmap of the bullet hole... if that makes sense... I'm not a programmer... I'm a finance guy, but... if I understand your code above, this would provide a way to draw the image without have to create (draw) a form?? And I assume this process might be quicker??

    Would appreciate any other suggestions you might have for doing this... typically it's 3 to 9 bullet holes... small file size bmp image

    thanks,

    Mag

    ReplyDelete
  2. with this snippet you can draw text(or a bitmap if you modify the code a bit) directly on the desktop's canvas(over all windows)
    focus issue can be solved by getting the active window before displaying the bullet(s) and after you display the bullets call SetForegroundWindow(handle to the previous active window)

    ReplyDelete

Blogroll(General programming and Delphi feeds)