Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a SetTimer() API in a console C++ application?

I have a console application that is using a DLL file that uses a SetTimer() call to create a timer and fire a function within itself. The call is below:

SetTimer((HWND)NULL, 0, timer_num, (TIMERPROC)UnSyncMsgTimer)) == 0) 

It is expecting to receive timer messages, but this never happens. I assume because mine is a console application and not a standard Windows GUI application (like where the DLL file was originally used). This stops a key part of the DLL files functionality from working.

My application needs to stay a console application, and I cannot change the DLL.

Is there a work around to make this work?

like image 556
JallenA1 Avatar asked Sep 23 '11 15:09

JallenA1


3 Answers

You can use CreateTimerQueueTimer function

HANDLE timer_handle_;
CreateTimerQueueTimer(&timer_handle_, NULL, TimerProc, user_object_ptr, 10, 0, WT_EXECUTEDEFAULT);
//callback
void TimerProc(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
    user_object* mgr = (user_object*) lpParameter;
    mgr->do();
    DeleteTimerQueueTimer(NULL, timer_handle_, NULL);
    timer_handle_ = NULL;
}
like image 179
Marx Yu Avatar answered Oct 25 '22 09:10

Marx Yu


Timers set using the SetTimer API require a Windows message processing function to be actively running, as that is where the time messages are sent.

If you need a timer thread then you could register a Window class and create a default window message pump (See this article for a short example), but a simpler process would probably be to just spin up a second thread to handle your timing events and send notifications.

like image 6
Chad Avatar answered Oct 25 '22 09:10

Chad


Have a look at the following example which shows how to use WM_TIMER messages with a console app:

(Credit to the Simple Samples site)

#define STRICT 1 
#include <windows.h>
#include <iostream.h>

VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) {
  cout << "Time: " << dwTime << '\n';
  cout.flush();
}

int main(int argc, char *argv[], char *envp[]) {
      int Counter=0;
      MSG Msg;
      UINT TimerId = SetTimer(NULL, 0, 500, &TimerProc);

      cout << "TimerId: " << TimerId << '\n';
      if (!TimerId)
        return 16;
      while (GetMessage(&Msg, NULL, 0, 0)) {
        ++Counter;
      if (Msg.message == WM_TIMER)
        cout << "Counter: " << Counter << "; timer message\n";
      else
        cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
      DispatchMessage(&Msg);
    }

    KillTimer(NULL, TimerId);

    return 0;
}
like image 4
Michael Goldshteyn Avatar answered Oct 25 '22 10:10

Michael Goldshteyn