项目截图:
先设计一个Timer类,用于计时,放在头文件Timer.h里面
class Timer
{
public:
Timer();
~Timer();
Timer operator++()
{
s++;
if (s >= 60)
{
s -= 60;
m++;
if (m >= 60)
{
m -= 60;
h++;
if (h >= 60)
{
h -= 60;
}
}
}
return *this;
}
Timer operator++(int)
{
Timer old = *this;
++(*this);
return old;
}
int getH() const
{
return h;
}
int getM() const
{
return m;
}
int getS() const
{
return s;
}
private:
int h, m, s;
};
Timer::Timer()
{
h = m = s = 0;
}
Timer::~Timer()
{
}
//---------------------------------------------------------------------
//创建一个线程回掉函数用于计时:
DWORD WINAPI clock1_proc(LPVOID lparam)
{
Timer t;
CString s;
while (true)
{
t++;
Sleep(1000);
s.Format(_T("%02d:%02d:%02d"), t.getH(), t.getM(), t.getS());
((CStatic*)lparam)->SetWindowTextW(s);
}
}
void CClockDlg::OnBnClickedStart()//开始按钮的代码
{
// TODO: 在此添加控件通知处理程序代码
if (hClock1)//从暂停里恢复,hClock1表示第一个clcok的线程句柄,
{
ResumeThread(hClock1);
}
else{
hClock1 = CreateThread(0, 0, clock1_proc, &this->hClock1Ctl, 0, NULL);//新建一个clock线程
}
}
void CClockDlg::OnBnClickedPause()//暂停按钮的代码
{
// TODO: 在此添加控件通知处理程序代码
if (hClock1)
{
SuspendThread(hClock1);
}
}
void CClockDlg::OnBnClickedReset()//重置按钮的代码
{
// TODO: 在此添加控件通知处理程序代码
if (hClock1)
{
TerminateThread(hClock1, 0);
hClock1Ctl.SetWindowTextW(_T("00:00:00"));
hClock1 = NULL;
}
}
源码下载:https://pan.baidu.com/s/134Qn9pBb0Hq32h7A_cQqzg