Wednesday, 21 November 2007

Creating a simple canvas subclass

So I created a simple subclass to answer a question on the RB Forum and made the mistake of saying I would write a simple description of how I did it.

Some of the detail of these instructions is influenced by the fact that I created it in the Windows IDE.

The sample project is on my website.

In the Project tab of a new project, I created a new class and set its Name to sjgTextBox and its Super to Canvas.

I double-clicked the new sjgTextBox class and in the tab that opened, I created a few properties to store the text details and the mouseDown position.

  • BorderColour and TextColour are public Color properties with default values.
  • When setting Text, I need to change the width of the control appropriately, so I created a computed property.
  • Private properties mDownX and mDownY as Integer will come in handy for remembering where the mouseDown occurred, when dragging.
In the setter for Text, I added code to resize the control based on the string width plus blank space the size of "W" at each end.

In the Paint event, I added code to draw a border around the control and the text property inside it.

In the mouseDown event, I added code to record the position of the mouse on the parent window.

In the mouseDrag event, I check whether the control is already positioned according to the mouse and, if not, I move it to the correct position on the parent window.

Going back to the Project tab, I right-clicked the sjgTextBox class and selected "Property List Behavior...", where I checked the three public properties I had created, so they would appear in the control's property-list.

The control was now complete, so the next job was to add some to a window.

I opened the window's code view and in the popupmenu above the control palette on the left, I selected "Project controls" and dragged 3 sjgTextBoxes onto the Window.
For each I set its Text property and the two Colour properties.

Compile and test.


GreenHLK said...

From the forum you pointed to:-"I can get along without it, but is there a reason for the absence of MouseDown?" - Any way you could expand your answer?

Steve Garman said...

I've added a BackGroundColour property to the sample code, as there was a question on the forums

@greenhlk, sorry I've only just seen your question. Will try to expand later.