开发者

TimerProc in c isn't working?

开发者 https://www.devze.com 2023-03-28 21:22 出处:网络
I\'m trying to write a callback for my timer. I defined the TimerProc like this: void CALLBACK TimerProc(HWND hwnd, UINT uMsg开发者_开发百科, UINT idEvent, DWORD dwTime)

I'm trying to write a callback for my timer. I defined the TimerProc like this:

void CALLBACK TimerProc(HWND hwnd, UINT uMsg开发者_开发百科, UINT idEvent, DWORD dwTime)
{
    //body of callback
}

and then the SetTimer defined like this:

myTimer = SetTimer(NULL,Timer_ID,30000,TimerProc);

my problem is that the callback never being called once the time elpassed (30 sec).

thank's for help.


SetTimer works by sending a WM_TIMER message to the default window procedure. Hence, as the MSDN states:

When you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER.

So make sure that you have a Message Loop running.


Quick test code. Works fine for me.

#include <windows.h>

static const TCHAR gc_szClassName[]   = TEXT("Test");
static const TCHAR gc_szWindowTitle[] = TEXT("Test");

#define IDT_TIMER 0x100

VOID CALLBACK TimerProc(HWND hWnd, UINT uMessage, UINT_PTR uEventId, DWORD dwTime)
{
  // display a message box to see the results of our beautiful program
  MessageBox(hWnd, TEXT("This should pop up every 10 seconds.."), TEXT("Yay!"), MB_OK | MB_ICONINFORMATION);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
  switch (uMessage)
  {
    case WM_CREATE:
      // run every 10 seconds
      SetTimer(hWnd, IDT_TIMER, 10000, TimerPRoc);
      break;

    case WM_CLOSE:
      DestroyWindow(hWnd);
      break;

    case WM_DESTROY:
      KillTimer(hWnd, IDT_TIMER);
      PostQuitMessage(EXIT_SUCCESS);
      break;
  }

  return DefWindowProc(hWnd, uMessage, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCommandLine, int nShowCommand)
{
  // define variables
  HWND hWnd;
  WNDCLASS wc;
  MSG msg;

  // unused parameters
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpszCommandLine);
  UNREFERENCED_PARAMETER(nShowCommand);

  // initialize WNDCLASS structure
  ZeroMemory(&wc, sizeof(wc));
  wc.lpfnWndProc = WndProc;
  wc.hInstance = hInstance;
  wc.lpszClassName = gc_szClassName;

  // attempt to register the class
  if (RegisterClass(&wc) != 0)
  {
    // attempt to create the window
    hWnd = CreateWindow(gc_szClassName, gc_szWindowTitle, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);
    if (hWnd != NULL)
    {
      // retrieve messages
      while (GetMessage(&msg, NULL, 0, 0) > 0)
      {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }

      // use the return-code from the window
      return (int)msg.wParam;
    }
  }
  return EXIT_FAILURE;  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消