I need to know how to properly use the SetTimer() function in C++ from windows.h.. Please helm me about this... I have this code, but it doesn't seem to have any result...
#include %26lt;windows.h%26gt;
#include %26lt;iostream%26gt;
#include %26lt;conio.h%26gt;
using namespace std;
HANDLE curhndl();
int i = 0;
void proc();
main()
{
void (*fptr)() = %26amp;proc;
SetTimer((HWND)curhndl(), 1, 1, fptr());
getch();
cout%26lt;%26lt;i;
getch();
}
void proc()
{
i++;
}
HANDLE curhndl()
{
static bool called;
static HANDLE hwnd;
if (called != true){
hwnd = GetStdHandle(STD_OUTPUT_HANDLE);
if (hwnd == INVALID_HANDLE_VALUE){ return INVALID_HANDLE_VALUE; }
called = true; }
return hwnd;
}
How do I fix this problem in C++?
I think there may be a few problems with the code. One that jumps out at me is in HANDLE curhndl().
You are not initializing 'static bool called', so it starts off as a garbage value (not 0). Since 'true' means 'not-zero', called will likely always be true. That means GetStdHandle never executes.
Hope that helps. Good luck!
Reply:Sorry to say, but your code is ABSOLUTELY incorrect. Sorry again :(
If you want to use API timers, you should spin message loop. The handle (that you pass to SetTimer) should be not the standard output or whatever, but a handle of a real window (that is why it is of HWND type)! If you pass to SetTimer something different from a window handle (even if you cast it to HWND as you smartly did :) ), the function will fail and will not create a timer.
I don't think it is a good idea to use API timers in console application at all - they are not designed to work this way. Try windowed application.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment