How to draw a crosshair

How to draw a crosshair

How to draw a crosshair

Use this tutorial to learn how to draw a crosshair on the form using mouse coordinates. Basic technique here is to erase previous cross and draw the new crosshair as mouse move.

DownloadDownload This Tutorials

Bookmark:

How to draw a crosshair

Use FormMouseMove procedure to draw the crosshair. Actually if you carefully check there is another procedure call DrawCross define inside the main procedure. We use this method because within this program DrawCross is call only from FormMouseMove procedure. So you can write the sub procedure within main procedure. DrawCross procedure is the one doing all the drawing for crosshair. By putting canvas pen mode to XOR enable erasing previous crosshair easily.

Draw crosshair on form

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,Y: Integer);

    { We wrote this procedure with in this block for easy access, this one draws the cross hair}
    Procedure DrawCross(AX,AY:Integer);
    Begin
        With Form1.Canvas Do
        Begin
              { By putting pen mode to Xor will help to
              erase the previous cross hair }
              Form1.Canvas.Pen.Mode:=pmNotXor;
              MoveTo(Ax,0);
              LineTo(Ax,Form1.Height);
              MoveTo(0,AY);
              LineTo(Form1.Width,AY);
        End;
    End;

begin
  If Not FirstMove Then
        DrawCross(OldX,OldY)
  Else
        FirstMove:=False;
  DrawCross(X,Y);
  Form1.Caption:='X : '+IntToStr(X)+' Y : '+IntToStr(Y);
  OldX:=X;
  OldY:=Y;
end;

In here FirstMove is a global variable define to identify the first time draw. It will help to erase the previous draw as mouse change its position. At the beginning set this to TRUE.

procedure TForm1.FormCreate(Sender: TObject);
begin
      FirstMove:=True;
end;

Download This Delphi Tutorials.

Download materials for this article (Delphi - Tutorials)

Download - draw-crosshair.zipdraw-crosshair.zip
       File size: 4 KB, File type: zip
       Total downloads: 439, Upload date: February 10 - 2009

AW :: August 04-2010 :: 04:36 AM

Hi, have you try this procedures on resizeable form ? and try to resize your form, and see what happended..

Leave a comment