c++ - 如何为使用 createwindow 创建的窗口创建自定义背景颜色

标签 c++ winapi backcolor

我对 C++ 相当陌生,并且正在尝试学习在使用 CreateWindow(或 CreateWindowEx)函数为注册类创建的窗口上获取自定义填充颜色的最佳方法。

我编写了一个程序,演示了 3 种方法都有效,但不确定哪种方法被认为是最好的。

比我更有经验的人可以评论吗?建议?最佳实践?

我的三种方法:

1)注册窗口时设置自定义背景颜色(在我的示例中为红色背景)

2) 处理 wm_erasebkgnd 消息(在我的示例中为绿色)

3)处理wm_paint并使用fillrect(在我的例子中为蓝色)

我还发现在 wm_erasebkgnd 中发回 return 语句会在不使用 wm_paint 时弄乱绿色或红色背景

提前致谢。

//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;
}

最佳答案

如果你想使用 WM_ERASEBKGND方法,然后你的 WindowProcedure应该自己做背景删除,而不是尝试重置类背景画笔。这是一个相当简单(且快速)的操作:

//...
    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;
    }
//...

注意:正如评论中指出的,它是 更有效地制作 HBRUSH对象一个“全局”变量,然后在程序启动时创建它(仅一次)并在退出时删除它。

随时要求进一步澄清和/或解释。

关于c++ - 如何为使用 createwindow 创建的窗口创建自定义背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61783088/

相关文章:

c++ - 通过构造函数初始化集初始化的变量的销毁顺序是什么?

c++ - 为什么 ATOMIC_FLAG_INIT 是假的?

windows - 是否可以将一个应用程序嵌入到 Windows 中的另一个应用程序中?

c# - 在 C# 中更改任何打开的窗体运行时的背景颜色

javascript - SlickGrid 在事件 onCellChange 上设置行背景颜色

java - 哪种语言介于 C++ 和 Java 之间?

c++ - 抽象声明符 Node* 用作声明

windows - 在没有 lodctr 的情况下注册性能计数器

c# - 如何通过拖动扩展窗口框架使 WPF 窗口可移动?