简体   繁体   English

如何为使用 createwindow 创建的 window 创建自定义背景颜色

[英]How to create custom background color for window created with createwindow

I am fairly new to C++ and am trying to learn the best way to get a custom fill color on a window created for a registered class using the CreateWindow (or CreateWindowEx) function. I am fairly new to C++ and am trying to learn the best way to get a custom fill color on a window created for a registered class using the CreateWindow (or CreateWindowEx) function.

I wrote a program demonstrating 3 methods that all work but am not sure which method is considered best.我编写了一个程序,演示了 3 种方法都有效,但不确定哪种方法被认为是最好的。

Can someone more experienced than me comment?比我更有经验的人可以评论吗? suggestions?建议? best practices?最佳实践?

My three methods:我的三种方法:

1) set a custom background color when registering the window (red background in my example) 1) 注册 window 时设置自定义背景颜色(在我的示例中为红色背景)

2) handle wm_erasebkgnd message (green color in my example) 2) 处理 wm_erasebkgnd 消息(在我的示例中为绿色)

3) handle wm_paint and use fillrect (blue color in my example) 3)处理wm_paint并使用fillrect(在我的例子中为蓝色)

I also found sending back a return statement in wm_erasebkgnd messes up the green or red backgrounds when wm_paint is not used我还发现在 wm_erasebkgnd 中发回一个 return 语句会在不使用 wm_paint 时弄乱绿色或红色背景

Thanks in advance.提前致谢。

//demonstrate different ways to customize the main window with a custom back color
//https://stackoverflow.com/questions/3463471/how-to-set-background-color-of-window-after-i-have- 
registered-it
//https://docs.microsoft.com/en-us/windows/win32/gdi/window-background?redirectedfrom=MSDN

#if defined(UNICODE) && !defined(_UNICODE)
#define _UNICODE
 #elif defined(_UNICODE) && !defined(UNICODE)
#define UNICODE
#endif

#include <tchar.h>
#include <windows.h>

//whichmethod = 0 --> red background (window registration background applies)
//whichmethod = 1 --> green background (wm_erasebkgnd used)
//whichmethod = 2 --> blue background (wm_paint is used)
#define Whichmethod 1 //0=no wm_paint and no WM_ERASEBKGND, color set in window registration
//#define Whichmethod 1 //1 = erasebkgnd method + window registration (wmerasebkgnd wins)
//#define Whichmethod 2 //2 = erasebkgnd method + wm_paint + window registration (wm_paint wins)

 //the return statement in wm_erasebkgnd can cause wm_erasebkgnd to change behavior, not sure why
 //set EraseRtn to 0 or 1 and if Whichmethod = 0 or 1 the screen is white, it is blue if Whichmethod = 2
 #define EraseRtn -1 //-1--> no return if WM_ERASEBKGND is called, next call is DefWindowProc
 //#define EraseRtn 1 //1 -> return a value of 1 if WM_ERASEBKGND is called, no call to DefWindowProc
 //#define EraseRtn 0 //0 -> return a value of 0 if WM_ERASEBKGND is called, no call to DefWindowProc

 /*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
TCHAR szClassName[ ] = _T("CodeBlocksWindowsApp");

int WINAPI WinMain (HINSTANCE hThisInstance,
                HINSTANCE hPrevInstance,
                LPSTR lpszArgument,
                int nCmdShow)
{
HWND hwnd;               /* This is the handle for our window */
MSG messages;            /* Here messages to the application are saved */
WNDCLASSEX wincl;        /* Data structure for the windowclass */

/* The Window structure */
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);

/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL;                 /* No menu */
wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
wincl.cbWndExtra = 0;                      /* structure or the window instance */

/* Original from Codeblocks generator: Use Windows's default colour as the background of the window
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
*/
wincl.hbrBackground = (HBRUSH) CreateSolidBrush(RGB(255, 0, 0)); //red background (works unless background color defined in wm_paint or wm_erasebkgnd)

/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
    return 0;

/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           _T("Code::Blocks Template Windows App"),       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
       );

/* Make the window visible on the screen */
ShowWindow (hwnd, nCmdShow);

/* Run the message loop. It will run until GetMessage() returns 0 */
while (GetMessage (&messages, NULL, 0, 0)) {
    /* Translate virtual-key messages into character messages */
    TranslateMessage(&messages);
    /* Send message to WindowProcedure */
    DispatchMessage(&messages);
}

/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
RECT rc;
PAINTSTRUCT ps;

switch (message) {                /* handle the messages */
case WM_DESTROY:
    PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
    break;

#if Whichmethod == 2
case WM_PAINT: {
    hdc = BeginPaint(hwnd, &ps);   // prepares the specified window for painting
    HBRUSH hcolor = CreateSolidBrush(RGB(0, 0, 255));//blue
    HGDIOBJ holdbrush = SelectObject(hdc, hcolor); // select the brush we want (hbrush) and store the previous brush holdbrush
    // SetBkMode( hdc, TRANSPARENT);     // sets the background mode to transparent (not needed for this exercise)
    // SetTextColor( hdc, RGB(255,255,255)) ;//white text, sets the text color
    GetClientRect (hwnd, &rc) ;  //retrieves the coordinates of the window's client area.
    FillRect(hdc, &rc, hcolor); //uses the new brush
    //for fun  DrawText(hdc,"DrawText: hello world",-1,&rc,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
 //draw text in the rectangle
    EndPaint(hwnd,&ps);  // marks the end of painting in the specified window.
    long retval = (long) SelectObject(hdc, holdbrush);  // select old brush
    bool tbool = DeleteObject(hcolor);  //destroy the new brush else gdi count grows
    return 0L;//says we processed the message
}
#endif

#if Whichmethod == 1 | WhichMethod == 2
case WM_ERASEBKGND: {
//this section doesn't repaint background if wm_paint uses fillrect and returns 0
    HBRUSH brush = CreateSolidBrush(RGB(0, 255, 0));//Green
    SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG_PTR)brush);
    //An application should return nonzero if it erases the background; otherwise, it should return zero.
#if EraseRtn == 1
    return 1l;//return 1 or 0 creates a problem, our custom (green or red) color is lost (white instead); blue from wm_paint is not affected
#endif // EraseRtn
#if EraseRtn == 0
    return 0l;
#endif // EraseRtn
//if here we don't return anything and we eventually call defwindowproc below
}
#endif //whichmethod 1 or 2


default:  /* for messages that we don't deal with */
    return DefWindowProc (hwnd, message, wParam, lParam);
}

return 0;
}

If you want to use the WM_ERASEBKGND method, then your WindowProcedure should itself do the background erasure, rather than trying to reset the class background brush.如果您想使用WM_ERASEBKGND方法,那么您的WindowProcedure应该自己进行背景擦除,而不是尝试重置 class 背景画笔。 It is a fairly trivial (and rapid) operation:这是一个相当简单(且快速)的操作:

//...
    case WM_ERASEBKGND: {
        HDC hdc = (HDC)(wParam); 
        RECT rc; GetClientRect(hwnd, &rc); 
        HBRUSH brush = CreateSolidBrush(RGB(0, 255, 0));//Green
        FillRect(hdc, &rc, brush); 
        DeleteObject(brush); // Free the created brush: see note below!
        return TRUE;
    }
//...

NOTE: As pointed out in the comments, it is far more efficient to make the HBRUSH object a 'global' variable, then create it (only once) on program startup and delete it on exit.注意:正如评论中所指出的,将HBRUSH HBRUSH设为“全局”变量,然后在程序启动时创建(仅一次)并在退出时将其删除,效率更高。

Feel free to ask for further clarification and/or explanation.随时要求进一步澄清和/或解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM