Sharing Code Among Event Handlers

From RAD Studio
Jump to: navigation, search

Go Up to Using Drawing Tools


Any time you find that many your event handlers use the same code, you can make your application more efficient by moving the repeated code into a routine that all event handlers can share.

To add a method to a form:

  1. Add the method declaration to the form object.You can add the declaration in either the public or private parts at the end of the form object's declaration. If the code is just sharing the details of handling some events, it's probably safest to make the shared method private.
  2. Write the method implementation in the implementation part of the form unit.

The header for the method implementation must match the declaration exactly, with the same parameters in the same order.

The following code adds a method to the form called DrawShape and calls it from each of the handlers. First, the declaration of DrawShape is added to the form object's declaration:

enum TDrawingTool {
	dtLine, dtRectangle, dtEllipse, dtRoundRect
};

class TForm1 : public TForm {
__published: // IDE-managed Components
	void __fastcall FormMouseDown(TObject *Sender, TMouseButton Button,
		TShiftState Shift, int X, int Y);
	void __fastcall FormMouseMove(TObject *Sender, TShiftState Shift,
		int X, int Y);
	void __fastcall FormMouseUp(TObject *Sender, TMouseButton Button,
		TShiftState Shift, int X, int Y);

private: // User declarations
	void __fastcall DrawShape(TPoint TopLeft, TPoint BottomRight,
		TPenMode AMode);

public: // User declarations
	__fastcall TForm1(TComponent* Owner);

	bool Drawing; // field to track whether button was pressed
	TPoint Origin, MovePt; // fields to store points
	TDrawingTool DrawingTool; // field to hold current tool
};

Then, the implementation of DrawShape is written in the .cpp file for the unit

void __fastcall TForm1::DrawShape(TPoint TopLeft, TPoint BottomRight,
	TPenMode AMode) {
	Canvas->Pen->Mode = AMode;
	switch (DrawingTool) {
	case dtLine:
		Canvas->MoveTo(TopLeft.x, TopLeft.y);
		Canvas->LineTo(BottomRight.x, BottomRight.y);
		break;
	case dtRectangle:
		Canvas->Rectangle(TopLeft.x, TopLeft.y, BottomRight.x, BottomRight.y);
		break;
	case dtEllipse:
		Canvas->Ellipse(TopLeft.x, TopLeft.y, BottomRight.x, BottomRight.y);
		break;
	case dtRoundRect:
		Canvas->Rectangle(TopLeft.x, TopLeft.y, BottomRight.x, BottomRight.y,
			(TopLeft.x - BottomRight.x) / 2, (TopLeft.y - BottomRight.y) / 2);
		break;
	}
}

The other event handlers are modified to call DrawShape.

void __fastcall TForm1::FormMouseUp(TObject *Sender) {
	DrawShape(Origin, Point(X, Y), pmCopy); // draw the final shape
	Drawing = false;
}

void __fastcall TForm1::FormMouseMove(TObject *Sender, TMouseButton Button,
	TShiftState Shift, int X, int Y) {
	if (Drawing) {
		DrawShape(Origin, MovePt, pmNotXor); // erase previous shape
		MovePt = Point(X, Y);
		DrawShape(Origin, MovePt, pmNotXor); // draw current shape
	}
}

See Also