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



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

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

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

我的三种方法:

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

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

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

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

提前谢谢。

//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://learn.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对象设置为"全局"变量,然后在程序启动时创建它(仅一次(并在退出时将其删除,效率要高得多

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

最新更新