Introduction
While writing a program that displays Mandelbrot images, I wrote some code to make it possible to select a region on a window form for zooming into the Mandelbrot image.
While doing so, I realized that this might be useful in other programs, and I split the region selection code off and put it into a class called SelectionForm
which is derived from System::Windows::Forms::Form
. The new class adds region selection functionality to the Form
class, and is pretty easy to use.
Using the code
Add the SelectionForm
.cpp and .h files into your C++ Windows Forms CLR project. Include SelectionForm.h in your Form1.h file.
#include "SelectionForm.h"
Derive your form class from SelectionForm
instead of System::Windows::Forms::Form
and do some initialization in the constructor of your form class.
public ref class Form1 : public SelectionForm
{
public:
Form1(void)
{
InitializeComponent();
this->Paint += gcnew
System::Windows::Forms::PaintEventHandler(this,
&SelectionForm::_Paint);
SelectionAspectRatio = 1.0f;
this->DoubleBuffered = true;
}
Users can use the mouse to create, resize, or move a region selection on your form. Your derived class can use the functions hasSelection
, getSelection
, and clearSelection
to get information about the region selection, as in the following example of a button click handler function:
private: System::Void button1_Click(System::Object^ sender,
System::EventArgs^ e) {
if (this->hasSelection()) {
System::Drawing::Rectangle^rect = this->getSelection();
System::Windows::Forms::MessageBox::Show(rect->ToString());
this->clearSelection();
} else {
System::Windows::Forms::MessageBox::Show("No Selection");
}
}
How does it work?
The derived class SelectionForm
has handlers for the mouse up, down, and move events. It also has a handler for the paint event. The mouse events are added to the form's eventshandler list in the constructor of SelectionForm
. The Paint
eventhandler must be added to the eventhandlerlist after the derived class' own Paint
handler, otherwise the painting occurs in the wrong order.
The class has some logic to keep track of the selection and the appearance of the mouse pointer.
Points of Interest
Annoying: Sometimes the IDE get confused when showing the [Design] view of your form because it is derived from something else then the standard form. Rebuilding the solution solves this problem.
Note: the demo application zooms to the selection by hitting the Enter-key, and zooms out again by hitting the Escape-key.