0

How do I make a timer work in c++ WM_PAINT? I'm trying to "print" it via Wm_Paint, because at the moment I don't know another method of adding a timer, googling didn't help.

Here's what I have declared in CALLBACK:

TCHAR s[10], str[20] = _T("Seconds: ");
    static int t;

case WM_CREATE:


        SetTimer(hwnd, 1, 1000, NULL);

And here's how I try to draw the timer:

hdc = BeginPaint(hwnd, &ps);
        hBrush = CreateSolidBrush(g_color);
        hPen = CreatePen(PS_NULL, 1, RGB(0, 0, 0));
        holdPen = HPEN(SelectObject(hdc, hPen));
        holdBrush = (HBRUSH)SelectObject(hdc, hBrush);

_tcscat(str + 9, _itot(t, s, 10));
        TextOut(hdc, 10, 300, str, _tcsclen(str));

SelectObject(hdc, holdBrush);
        SelectObject(hdc, holdPen);
        DeleteObject(hPen);
        DeleteObject(hBrush);
        EndPaint(hwnd, &ps);

So far, it just prints out "Seconds: 0" and stops updating.

dapet
  • 69
  • 8
  • Questions seeking debugging help should generally provide a [mre] of the problem, which includes a function `main` (or `WinMain`) and all `#include` directives. – Andreas Wenzel Mar 23 '22 at 14:14
  • Managed to fix it by adding a WM_TIMER case, where I increment the int t and do InvalidateRect – dapet Mar 23 '22 at 14:24
  • Regarding your code snippet that you have labelled "And here's how I try to draw the timer", is that code inside the window procedure under the `WM_PAINT` case of the `switch` statement? Or is it under `WM_TIMER`? Please [edit] your question to clarify it. – Andreas Wenzel Mar 23 '22 at 14:29
  • 2
    Yes, the solution that you posted as a comment sounds good. Note that you can post an answer to your own question. See the following official help page for further information: [Can I answer my own question?](https://stackoverflow.com/help/self-answer) This may be more appropriate than posting your solution as a comment to your question. However, unless you improve your question, in my opinion, it may be more appropriate to delete your question instead. – Andreas Wenzel Mar 23 '22 at 14:31
  • What do you expect `SetTimer(hwnd, 1, 1000, NULL);` to do? It tells the computer to do something every 1000 milliseconds... it tells the computer to do *what* every 1000 milliseconds? – user253751 Mar 23 '22 at 14:39

1 Answers1

3

Ok so, for me to make it work, I've had to create a WM_TIMER case in my CALLBACK function, in the end it looked like this:

//code above

case WM_TIMER:
t++;
InvalidateRect(hwnd, NULL, TRUE);
break;

//code below
dapet
  • 69
  • 8