Author: William Egge
For example a paint program requires that the mouse do different things depending
on what mode you are in, or maybe you have built a 3D world editor or vector
editor. Want a clean way to handle all those mouse actions without cluttering your
form code?
Answer:
The answer to the problem is to create mouse handler classes which your form passes
mouse actions to it - or even key strokes.
A mouse handler class would look like this. You can add key events of other events
if you like but I'll keep this simple.
1 TMouseHandler = class
2 procedure MouseDown(Sender: TObject; Button: TMouseButton;
3 Shift: TShiftState; X, Y: Integer); virtual; abstract;
4 procedure MouseMove(Sender: TObject; Shift: TShiftState; X,
5 Y: Integer); virtual; abstract;
6 procedure MouseUp(Sender: TObject; Button: TMouseButton;
7 Shift: TShiftState; X, Y: Integer); virtual; abstract;
8 end;
Then you would make descendents of this class to handle diffent "modes" for
example:
9 TDrawLine = class(TMouseHandler) {...};
10 TPaint = class(TMouseHandler) {...};
11 TDrawSquare = class(TMouseHandler) {...};
You do not have to apply this to just a paint program, the teqnique can be applied
to any app where the mouse must do different things.
The mouse events of the control will be forwarded to the current mouse handler.
For example:
12
13 procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
14 Shift: TShiftState; X, Y: Integer);
15 begin
16 Handler.MouseDown(Sender, Button, Shift, X, Y)
17 end;
18
19 procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
20 Y: Integer);
21 begin
22 Handler.MouseMove(Sender, Shift, X, Y)
23 end;
24
25 procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
26 Shift: TShiftState; X, Y: Integer);
27 begin
28 Handler.MouseUp(Sender, Button, Shift, X, Y);
29 end;
I'll make a note here that you may also want to include the ability for the handler
to paint. For example when drawing a line you may want to display a line as the
mouse moves.
When it is time to switch modes, simply reassign the "Handler" variable with a different type instance and your main form code is kept clean.
|