将文本放到运行时注册的静态控件中

putting text to static control registered at runtime

本文关键字:静态控件 注册 运行时 文本      更新时间:2023-10-16

我想在主窗口注册一个静态控件,然后用一些文本填充它。

完整代码:

#include <windows.h>
#include "resource.h"
#include <commctrl.h>
void RegisterCommonControls();
#pragma comment(lib, "comctl32.lib")
HINSTANCE hInstance;
HINSTANCE hPrevInstance;
int nCmdShow;
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch (Msg)
    {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
            return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
}
LRESULT CALLBACK LblStateProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    return DefWindowProc(hWnd, Msg, wParam, lParam);
}
void RegisterCommonControls()
{
    INITCOMMONCONTROLSEX iccex;
    iccex.dwSize = sizeof(INITCOMMONCONTROLSEX); 
    iccex.dwICC  = ICC_TREEVIEW_CLASSES | ICC_LISTVIEW_CLASSES; 
    InitCommonControlsEx(&iccex);
}
bool RegisterWindow(void)
{
    if (hPrevInstance)
        return false;
    WNDCLASS wc;
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = MainWndProc;
    wc.cbClsExtra   = wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(0, IDI_APPLICATION);
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
    wc.lpszMenuName = MAKEINTRESOURCE(IDC_WIN_API);
    wc.lpszClassName = L"Class1";
    if (!RegisterClass(&wc))
        return false;
    return true;
}
bool RegisterEdit(void)
{
    if (hPrevInstance)
        return false;
    WNDCLASS wc;
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = LblStateProc;
    wc.cbClsExtra   = wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = wc.hCursor = NULL;
    wc.hbrBackground = (HBRUSH)(GetStockObject(WHITE_BRUSH));
    wc.lpszMenuName = NULL;
    wc.lpszClassName = L"STATIC";
    if (!RegisterClass(&wc))
        return false;
    return true;
}
int CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    const int size = 600;
    MSG msg;
    RegisterWindow();
    HWND hMainWnd = CreateWindow(L"Class1", L"Main Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, size, size, 0, 0, hPrevInstance, NULL);
    RegisterCommonControls();
    RegisterEdit();
    HWND hLblState = CreateWindow(L"STATIC", L"1", WS_CHILD | WS_VISIBLE | SS_SIMPLE | SS_OWNERDRAW, 200, 200, 100, 50, hMainWnd, 0, NULL, NULL);
    ShowWindow(hMainWnd, nCmdShow);
    UpdateWindow(hMainWnd);
    SendMessage(hLblState, WM_SETTEXT, NULL, (LPARAM)L"Rectangle");
    while(GetMessage(&msg, 0, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

所以,我在主窗口内得到一个白色的"静态"窗口(控件在正确的坐标),里面没有文本(既不是"1"也不是"矩形")。我的代码有什么问题?

您正在注册一个名为"STATIC"的窗口类。这优先于内置的"STATIC"窗口类,因此您的窗口不会像静态控件那样运行。

要解决这个问题,不要注册一个名为"STATIC"的窗口类。