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 ) :
Event | Action |
---|---|
OnMouseDown | get 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.
GREAT...
ReplyDeleteCode is not working
ReplyDeleteit's work!!
ReplyDeletethx.. keep posting (y)
Old post, but still useful. Thanks for sharing!
ReplyDeletetank's for help
ReplyDelete