admin管理员组

文章数量:1434929

In the following code, I set a timer to display a MessageBox every one hundred milleseconds, but the timer seems to be not called at all.

I create the timer in WM_CREATE with SetTimer(hwnd, 1, 100, timer_proc). In the callback function timer_proc, I use MessageBox to show a MessageBox every time the timer callback is called: MessageBoxA(hwnd, "TIMER PROC CALLED!", "MSGBOX", 0).

After compilation and run, the window is successfully created, however there are no MessageBoxes shown, implying that the timer callback function is not called. Why is that?

The following is the code:

#include <windows.h>

VOID CALLBACK timer_proc(HWND hwnd, UINT msg, UINT timer_id, DWORD time)
{
        MessageBoxA(hwnd, "TIMER PROC CALLED!", "MSGBOX", 0);
}

LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
        switch (msg) {
        case WM_CREATE:
                SetTimer(hwnd, 1, 100, timer_proc);
                return 0;
        case WM_PAINT: return 0;
        case WM_SIZE: return 0;
        case WM_DESTROY: PostQuitMessage(0); return 0;
        default: return DefWindowProc(hwnd, msg, wp, lp);
        }
}

void init_wndclass(WNDCLASS *w, HINSTANCE hinstance, char *class_name)
{
        w->style = CS_HREDRAW | CS_VREDRAW;
        w->lpfnWndProc = wndproc;
        w->cbClsExtra = w->cbWndExtra = 0;
        w->hInstance = hinstance;
        w->hIcon = LoadIcon(NULL, IDI_APPLICATION);
        w->hCursor = LoadCursor(NULL, IDC_ARROW);
        w->hbrBackground = GetStockObject(WHITE_BRUSH);
        w->lpszMenuName = NULL;
        w->lpszClassName = class_name;
}

HWND create_window(HINSTANCE hinstance)
{
        WNDCLASS wndclass;
        char *class_name = "main window class";
        init_wndclass(&wndclass, hinstance, class_name);
        RegisterClass(&wndclass);
        return CreateWindowA(class_name, "TIMER TEST", WS_OVERLAPPEDWINDOW,
                        CW_USEDEFAULT, CW_USEDEFAULT, // position
                        CW_USEDEFAULT, CW_USEDEFAULT, // window size
                        NULL, /* owner window */ NULL, /* menu */
                        hinstance, NULL /* window-creation data */);
}

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev, PSTR cmdline,
                   int cmdshow)
{
        HWND hwnd = create_window(hinstance);
        ShowWindow(hwnd, cmdshow);
        UpdateWindow(hwnd);

        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0))
        {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
        }
}

本文标签: cTimer callback is not calledStack Overflow