VS控制台下计时器的问题
我想编一个控制台下的程序,想为程序加一个计时器,可是计时器只有在鼠标动的时候才会更新时间
下面是我的代码:
while (true)
{
if (a[m-1][n-1]==0)
{
system("CLS");
printf("YOU WIN IT");
Sleep(5000);
ExitProcess(0);
}
SetConsoleMode(hStdin, fdwMode);
ReadConsoleInput(hStdin, &InBuf, 1, &cNumRead);
if (MouseClick(InBuf))
{
x=(InBuf.Event.MouseEvent.dwMousePosition.X-StartX)/2;
y=InBuf.Event.MouseEvent.dwMousePosition.Y-StartY;
if ((x>=0) && (x<=n-1)&&(y>=0)&&(y<=m-1)&&(a[y][x]>0))
{
flood(a,m,n,y,x);
gotoXY(0,0);
PrintBubble(a,m,n);
}
}
gotoXY(0,m);
PrintTime(StarTime);
}
我自己通过调试,确定问题应该在ReadConsoleInput(hStdin, &InBuf, 1, &cNumRead)这一句上,程序应该是在这里进入了一个循环,等待捕获鼠标事件,于是我尝试着加上判断,即修改成
if (!(ReadConsoleInput(hStdin, &InBuf, 1, &cNumRead)))
gotoXY(0,m);
PrintTime(StarTime);
后面跟上原来的内容,但是问题并没有解决
求高手帮忙看看
[解决办法]
参考下以下代码:
#include <windows.h> #include <iostream> using namespace std; static BOOL bExitApp = FALSE; const UINT uiTimerID = 10; TIMERPROC FooTimerFun( HWND, UINT, UINT, DWORD ) { static int nCount = 0; cout << "Timer Function , nCount = " << nCount ++ << endl; if( nCount > 20 ) bExitApp = TRUE; return 0;} int main() { MSG msgFoo; SetTimer( NULL, uiTimerID, 100 , (TIMERPROC)FooTimerFun ); while( !bExitApp && GetMessage( &msgFoo , NULL , 0 , 0 ) ) { TranslateMessage( &msgFoo ); DispatchMessage( &msgFoo ); } KillTimer( NULL , uiTimerID ); return 0; }
[解决办法]
也可以另开一个线程,在那个线程里面
while (1) {
Sleep(1000);
显示计时
if (exitloop) break;
}