1

I develop a win32 app and create a color chooser using this example. I update if statement like this to change the background of my app when user click to "Ok" in color dialog box, but nothing change. Where is my mistake?

if (ChooseColor(&cc) == TRUE) {
    HBRUSH hbrush = CreateSolidBrush(cc.rgbResult);
    rgbCurrent = cc.rgbResult;
    SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND, (LONG)hbrush);
}
Community
  • 1
  • 1
rel1x
  • 2,351
  • 4
  • 34
  • 62

1 Answers1

2

The following code would work.

First, SetClassLongPtr() returns the previous value, which is, in this case, the HBRUSH previously set to the window class(hWnd). You should delete the object to avoid memory leak.

After that, calling InvalidateRect() brings the color change into effect. Because the newly created brush will be used when the window needs to be repainted.

InvalidateRect() sends WM_ERASEBKGND to the window.

if (ChooseColor(&cc) == TRUE) {
    HBRUSH hbrush = CreateSolidBrush(cc.rgbResult);
    HBRUSH hOldBrush = (HBRUSH)SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND, (LONG_PTR)hbrush);

    DeleteObject(hOldBrush);
    InvalidateRect(hWnd, NULL, 1);
}
Chanhee Jo
  • 199
  • 6
  • 1
    Note that this changes the background color for all Windows of the class, not just the one represented by `hWnd`. You should custom erase the window with `WM_ERASEBKGND` so that only the one window changes its background color. – Raymond Chen Mar 28 '16 at 03:36