Newbie_Programmer
Newbie_Programmer

Reputation: 21

Timer in C language on Windows

I am making a Quiz program. A question is displayed and a timer starts. The user has to answer the question in 30 seconds. If he doesn't answer the question during the 30 seconds, the timer ends and the next question is displayed. The problem is that all the TIMER programs i have come across stop the program i.e. user won't be able to input his answer during that timer

Upvotes: 0

Views: 464

Answers (1)

Bernd Elkemann
Bernd Elkemann

Reputation: 23560

The correct way to do this is to not use threads or 0.1-second sleeps.

You should get a little Windows application from some tutorial (you recognize a typical example Windows application by a WinMain() instead of a main()).

You can then add these functions:

SetTimer and KillTimer

Here's a full working example: It creates a window with a text-input, gives it focus and sets a timer to 1 second. When the timer expires it gets the text from the text-input and shows it in a dialog-box.

#include <windows.h>

HWND hwndMain = 0;
HWND hwndEdit = 0;
#define idTimer 123
VOID CALLBACK TimerProc(HWND w, UINT msg, UINT_PTR e, DWORD t) {
  Beep(2000, 10);
  KillTimer(hwndMain, idTimer);
  char tmp[100];
  GetWindowText(hwndEdit, tmp, 100);
  MessageBox(0, tmp, "you entered:", 0);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l)
{
  #define id_note 50

    switch(msg) {
      case WM_CREATE:
        hwndMain = hwnd;
        hwndEdit = CreateWindowEx(WS_EX_CLIENTEDGE,"EDIT",
        "",WS_CHILD|WS_VISIBLE,
        0,0,80,20,hwnd,(HMENU)id_note,GetModuleHandle(0), 0);
        SetFocus(hwndEdit);
        SetTimer(hwndMain, idTimer, 1000, TimerProc);
      break;
      case WM_CLOSE:
          DestroyWindow(hwnd);
      break;
      case WM_DESTROY:
          PostQuitMessage(0);
      break;
      default:
        return DefWindowProc(hwnd, msg, w, l);
    }
    return 0;
}

const char g_szClassName[] = "myWindowClass";
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;
    memset(&wc, 0, sizeof(WNDCLASSEX));
    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.lpfnWndProc   = WndProc;
    wc.hInstance     = hInstance;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = LoadIcon(0, IDI_APPLICATION);

    RegisterClassEx(&wc);

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        0, 0, hInstance, 0);

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&Msg, 0, 0, 0) > 0) {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

Upvotes: 3

Related Questions