最簡單的模擬計時器:
#include<stdio.h>
#include<conio.h>
#include<windows.h>
int m=0,s=0,ms=0;? //m是分 s是秒 ms是毫秒
//以下是5個自編函數void csh( );? //初始化界面
void yinc(int x,int y);? //隱藏光標的函數(y值設為0就會隱藏)
void jishi( ); ?//計時器運行(每100毫秒變化壹次)
void Color (short x, short y); ?//設定顏色的函數(y設為0就是黑底)
void gtxy (int x, int y); ?//控制光標位置的函數
int main(? )? //主函數
{? csh( );
? getch( );
? while(1)
? { jishi( );
Sleep(100);? //間隔100毫秒
if( kbhit( ) )break;? //有鍵按下就退出循環
? }
return 0;
}
void csh( ) ? //初始化界面
{Color(14,0); ? //設定淡黃字配黑底
printf(“\n\n\t 計時器”);
Color(10,0); ? //設定淡綠字配黑底
printf("\n\t┌───────────┐");
printf("\n\t│ │");
printf("\n\t└───────────┘");
gtxy(10,4); ? //光標到屏幕第10列4行處輸出
Color(7,0); ? //恢復白字黑底
printf(" 00:00:00 ");
yinc(1,0 ); ? //隱藏光標(yinc代表隱藏)
return;
}
void jishi( )? //計時器運行
{ms+=1;
if(ms==10){s+=1;ms=0;} if(s==60){m+=1;s=0;} gtxy(10,4); Color(9,0); ? //設定淡藍字配黑底 if(m>9) printf(" %d:",m); else printf(" 0%d:",m); Color(14,0); ? //設定淡黃字配黑底 if(s>9) printf("%d:",s); else printf("0%d:",s); Color(12,0); ?//設定淡紅字配黑底 printf("0%d",ms);}
void gtxy (int x, int y) ? //控制光標位置的函數
{ COORD pos;
pos.X = x;? pos.Y = y;? SetConsoleCursorPosition ( GetStdHandle (STD_OUTPUT_HANDLE), pos );}
void Color (short ForeColor= 7, short BackGroundColor= 0) ? //設定顏色的函數
{ HANDLE? handle = GetStdHandle ( STD_OUTPUT_HANDLE );
SetConsoleTextAttribute ( handle, ForeColor + BackGroundColor * 0x10 );}
void yinc(int x,int y) ? //隱藏光標的設置(gb代表光標)
{ CONSOLE_CURSOR_INFO ?gb={x,y}; ? //x為1-100,y為0就隱藏光標
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &gb); }