OnPaint event example for C++ Builder
1. |
Start with the project that you created in Loading and Displaying an Image. |
2. |
Add the following line to Unit1.h: |
#include <stdlib.h>
3. |
Add the following declarations to the private section of the Unit1.h file: |
RECT MyRect; /*Used with the OnPaint event example*/
POINT MyPoint; /*Used with the OnPaint event example*/
4. |
Add a button to the top of your main form, and in the Object Inspector box, change both its name and caption to Toggle. |
5. |
Add an edit box to the top of your form, and in the Object Inspector box, change its name to Directions, and change its Text property to the following: |
Use the Toggle button to turn on or turn off Click-Splat
6. |
Code the Toggle button's Click procedure as follows. This code uses the Enabled property to toggle the LEAD control's ability to respond to click events. |
void __fastcall TForm1::ToggleClick(TObject *Sender)
{
if(!Lead1->Enabled)
{
Lead1->Enabled = True;
Directions->Text = "Click on the image for a splat";
Toggle->Caption = "Disable";
}
else
{
Lead1->Enabled = False;
Directions->Text = "Click does nothing";
Toggle->Caption = "Enable";
}
}
7. |
Code the LEAD control's Click procedure as follows. When the Enabled property is true, this code uses a Windows API call to generate an OnPaint event. |
void __fastcall TForm1::Lead1Click(TObject *Sender)
{
THandle hCtl;
/*Do not use this event until the user enables it.*/
if (Toggle->Caption != "Disable")
return ;
/* Use InvalidateRect to generate a paint message*/
MyRect.left = 0;
MyRect.top = 0;
MyRect.bottom = Lead1->Height;
MyRect.right = Lead1->Width;
hCtl = (THandle)Lead1->Handle;
InvalidateRect((HWND)hCtl, &MyRect, TRUE);
}
8. |
Code the LEAD control's Paint procedure as follows. The procedure uses Windows GDI functions to draw random lines on the control whenever there is an OnPaint event. |
void __fastcall TForm1::Lead1Paint (TObject *Sender)
{
int i, xStart, yStart, xDelta, yDelta, xEnd, yEnd ;
HDC LeadClientDC;
/*Do not use this event until the user enables it.*/
if( Toggle->Caption != "Disable")
return;
MyPoint.x = 0;
MyPoint.y = 0;
/* Create a device context for the control that the GDI functions can access*/
LeadClientDC = (HDC)Lead1->GetClientDC();
/* Draw random lines on the control. This is an overlay that does not affect the bitmap.*/
xStart = random(Lead1->Width + 1);
yStart = random(Lead1->Height + 1);
MoveToEx(LeadClientDC, xStart, yStart, &MyPoint);
for (i=1; i<=50; i++)
{
xDelta = random(81) - 40;
yDelta = random(81) - 40;
xEnd = xStart + xDelta;
yEnd = yStart + yDelta;
LineTo(LeadClientDC, xEnd, yEnd);
MoveToEx(LeadClientDC, xStart, yStart, &MyPoint);
}
/* Remove the lock from the device control*/
Lead1->ReleaseClientDC();
}
9. |
Run your program to test it. |