Mirror

Technique for handling mouse actions (Views: 108)


Problem/Question/Abstract:

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.

TMouseHandler = class
  procedure MouseDown(Sender: TObject; Button: TMouseButton;
    Shift: TShiftState; X, Y: Integer); virtual; abstract;
  procedure MouseMove(Sender: TObject; Shift: TShiftState; X,
    Y: Integer); virtual; abstract;
  procedure MouseUp(Sender: TObject; Button: TMouseButton;
    Shift: TShiftState; X, Y: Integer); virtual; abstract;
end;

Then you would make descendents of this class to handle diffent "modes" for example:

TDrawLine = class(TMouseHandler) {...};
TPaint = class(TMouseHandler) {...};
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:

procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Handler.MouseDown(Sender, Button, Shift, X, Y)
end;

procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  Handler.MouseMove(Sender, Shift, X, Y)
end;

procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Handler.MouseUp(Sender, Button, Shift, X, Y);
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.

<< Back to main page