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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何为使用createwindow创建的窗口创建自定义背景颜色相关的知识,希望对你有一定的参考价值。

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

我编写了一个程序,演示了3种方法都可以使用,但是不确定哪种方法最好。

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

我的三种方法:

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

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

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

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

提前感谢。

//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方法,那么您的WndProc应该自身进行背景擦除,而不是尝试重置类背景画笔。这是一个相当琐碎(且快速)的操作:

//...
    case WM_ERASEBKGND: {
        HDC hdc = (HDC)(wParam); 
        RECT rc; GetClientRect(hwnd, &rc); 
        FillRect(hdc, &rc, hbrWhite); 
        return TRUE;
    }
//...

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

以上是关于如何为使用createwindow创建的窗口创建自定义背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

如何为 Presto 编写自定义窗口函数?

我使用vc++编程,我使用RegisterClassEx注册了窗口类,怎么用CreateWindow创建该类的MDI窗口?

创建窗口中的 hInstance

如何为主窗口创建的窗口小部件创建QCloseEvent

如何为主窗口创建的小部件创建 QCloseEvent

Electron.js:如何为一个窗口创建一个单独的下载 webContents.session?