HomeC&C++WainTutorialsSamplesTip&TrickTools


We will now let the user choose which color to use when drawing.
To do that we modify the toolbar so the user can select color by pressing a button on it.
The original toolbar used system default images, but we can't use them here, so we start of by creating a bitmap file:

The size of each part must be 16 by 16 pixels, the image contains 5 images, and is thus 80 pixels wide.
When we create the Toolbar we must first create a bitmap-handle from the image file:
   HBITMAP ToolBarBitmap = (HBITMAP )LoadImage(0,
                                               "toolbar.bmp",
                                               IMAGE_BITMAP,
                                               80,
                                               16,
                                               LR_LOADFROMFILE);
We then tell the toolbar to use this bitmap-handle:
   TBADDBITMAP TBaddBitmap;
   TBaddBitmap.hInst = 0;
   TBaddBitmap.nID   = (UINT )ToolBarBitmap;
   SendMessage(ToolBarWindow,
               TB_ADDBITMAP,
               (WPARAM )NumButton,
               (LPARAM )&TBaddBitmap);
We have tree colors, but only one can be active at a time, so we will let a button stay pushed until the user push another button in the same group. To do that we create the buttons with the TBSTYLE_CHECKGROUP style and not TBSTYLE_BUTTON. The default should have the TBSTATE_CHECKED state set, to indicate that it is selected.
If red is default we could create its button with:
   idx = SendMessage(ToolBarWindow,
                     TB_ADDSTRING,
                     0,
                     (LPARAM )"Red");
   ButtonInfo[4].iString = idx;
   ButtonInfo[4].iBitmap = 2;
   ButtonInfo[4].idCommand = DrawRedCmd;
   ButtonInfo[4].fsState = TBSTATE_ENABLED | TBSTATE_CHECKED;
   ButtonInfo[4].fsStyle = TBSTYLE_CHECKGROUP;
ButtonInfo[].iBitmap is the index into the bitmap, that is, the square starting at 16*index.
The other buttons are created the same way, they just does not have the TBSTATE_CHECKED state.
We will then add handlers for the tree buttons, in the windows proc:
         case DrawRedCmd:
            CurrentColor = RGB(255, 0, 0);
            break;
         case DrawBlueCmd:
            CurrentColor = RGB(0, 0, 255);
            break;
         case DrawGreenCmd:
            CurrentColor = RGB(0, 255, 0);
            break;
We will set the color for the line class in it's constructor, the LineClass will then look like this:
class LineClass
{
public:
   LineClass(POINT aStart, COLORREF aColor) :
      Start(aStart),
      End(aStart),
      Color(aColor),
      First(true)
   {}

   void SetEnd(HDC &aDc, POINT aEnd)
   {
      Draw(aDc, true);
      End = aEnd;
      Draw(aDc, true);
   }
   void Draw(HDC &dc, bool aMoving = false);
private:
   POINT Start;
   POINT End;
   COLORREF Color;
   bool First;
};
The Draw function must then create the pen in the correct color.
The complete code for the application can be found here