在 MFC 应用程序中使用 settimer() 时遇到问题

Having trouble using settimer() for MFC application

我设置了这段代码,这样我就可以为扫雷游戏设置计时器,但我无法编译它。

    void CALLBACK CMineSweeperBoard::clock(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime)
{
    if (t_seconds < 59){ t_seconds++; }
    else{
     t_minutes++;
     t_seconds = 0;
    }   
}

void CMineSweeperBoard::timer(void)
{
    MSG msg;

    SetTimer(NULL, 0, 1000, (TIMERPROC) &clock);
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
}

问题似乎与设置定时器函数中的参数有关,但我找不到它是什么,任何帮助将不胜感激。

您需要 SetTimerKillTimerON_WM_TIMER()。请参阅本页底部的示例: https://msdn.microsoft.com/en-us/library/49313fdf.aspx

不要在其中放置消息循环 While(GetMessage()...)

你可以通过调用 SetTimer(1, 1000, NULL); 来启动一个 1 秒的计时器,然后将 ON_WM_TIMER() 添加到消息映射,它将结果传递给 void CMyWnd::OnTimer(UINT nIDEvent) 这样你就不需要定义你的自己的TimerProc

或者您可以提供自己的 TimerProc,但 TimerProc 函数必须声明为 static。这可能很不方便,因为静态成员函数无法访问成员数据。使用 WM_TIMER 会更容易。