Reputation: 2581
The codes below is in winmain function after registering a class for the parent window:
RECT disrect;
HWND stat = CreateWindow("BUTTON","abcdef",
WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,10,150,500,100,dis,0,0,0);
HDC hdc=GetDC (stat);
FillRect(hdc,&disrect,CreateSolidBrush(RGB(3,5,54)));
SetTextColor(hdc,RGB(25,250,250));
POINT p[3];
p[1].x=280;
p[1].y=280;
p[2].x=280;
p[2].y=290;
p[3].x=285;
p[3].y=285;
Polygon(hdc,p,3);
TextOut(hdc,10,10,"hhhhh",5);
But when I run it, only shows a white rectangle into the parent window, neither the rect is filled with black brush, nor there is any text in it.
Could you guys tell me where I am wrong?
Upvotes: 1
Views: 67
Reputation: 11578
A few issues, in addition to not using WM_PAINT
.
First, merely calling CreateSolidBrush()
is not enough to mark that brush as the one for your drawing operations to use. You have to select the brush into a DC (device context) before you can use it. This is done with the SelectObject()
function. General usage looks like
HBRUSH prevBrush;
prevBrush = SelectObject(hdc, newBrush);
// drawing functions
SelectObject(hdc, prevBrush);
Yes, it is important to restore the previous brush when finished, even on a fresh DC; the initial state must be restored. The initial state uses a brush that draws nothing; this is why your Polygon()
doesn't draw anything. SelectObject()
is used for all the various things you use to draw with (pens, fonts, etc.), not just brushes.
Second, in C array indices start at 0 and go to size - 1
, not start at 1 and go to size
. So instead of saying pt[1]
, pt[2]
, and pt[3]
, you say pt[0]
, pt[1]
, and pt[2]
. Your compiler should have warned you about this.
Third, as the documentation for CreateSolidBrush()
will have said, once you are finished with the brush you must destroy it with DeleteObject()
. You must do this after selecting the previous brush back in. You must also do this with the brush you used in the FillRect()
call.
Upvotes: 1
Reputation: 148860
Unless you want to display animations, you should never try to directly write to a window that way, because many events could cause the window to redraw itself erasing what you have just written.
The correct way is to put it in the WM_PAINT handler.
Upvotes: 1