Monday, 12 April 2010

Click and Drag Mouse to Draw a Line Using Delphi

To draw a line with click and drag method, we use some events related with mouse : OnMouseDown, OnMouseMove and OnMouseUp. OnMouseDown is an event when we push the left mouse button. OnMouseMove is when we move the cursor. And OnMouseUp is when we release the mouse button. First, prepare a user interface ( a blank form and a button) :

Now, you have to decide what action should be done on each event ( OnMouseDown, OnMouseMove and OnMouseUp ) :

EventAction
OnMouseDownget the x and y start point
OnMouseMove - delete the old line
- draw the new line
OnMouseUp- draw the line
- finish drawing

The complete source code is listed below :

unit Unit1;

interface

uses

  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

  StdCtrls;

type

  TForm1 = class(TForm)

    Button1: TButton;

    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;

      Shift: TShiftState; X, Y: Integer);

    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,

      Y: Integer);

    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;

      Shift: TShiftState; X, Y: Integer);

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

  Drawing : boolean;

  StartX, StartY, EndX, EndY : integer;

implementation

{$R *.DFM}

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

begin

 Drawing := true;

 StartX := x;

 StartY := y;

 EndX := x;

 EndY := y;

end;

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

  Y: Integer);

begin

 if Drawing then

  begin

   Canvas.Pen.Mode := pmNotXor;

   Canvas.MoveTo(StartX,StartY);

   Canvas.LineTo(EndX,EndY);

   Canvas.MoveTo(StartX,StartY);

   Canvas.LineTo(x,y);

  end;

 EndX := x;

 EndY := y;

 Canvas.Pen.Mode := pmCopy;

end;

procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

begin

 Canvas.MoveTo(StartX,StartY);

 Canvas.LineTo(x,y);

 Drawing := false;

end;

procedure TForm1.Button1Click(Sender: TObject);

begin

 Application.Terminate;

end;

end.

Run the program, and now you can click and drag your mouse to draw a line.

5 comments:

These links are part of a pay per click advertising program called Infolinks. Infolinks is an In Text advertising service; they take my text and create links within it. If you hover your mouse over these double underlined links, you will see a small dialog box containing an advertisement related to the text. You can choose to move the mouse away and go on with your browsing, or to click on the box and visit the relevant ad. Click here to learn more about Infolinks Double Underline Link Ads.