Visual c++ 使用带vc+的OnTimer(UINT U PTR ID)的2个计时器+;
我想使用visual studio VC++2010类库使用两个计时器,一个用于读取传感器,另一个用于向机器人发出命令 如果单击按钮1,则第一个计时器打开,第二个计时器使用按钮3 但当我点击按钮2时,即使我没有按下按钮1,我的读取传感器仍在工作,反之亦然 这是我的节目: 我的代码有什么问题Visual c++ 使用带vc+的OnTimer(UINT U PTR ID)的2个计时器+;,visual-c++,timer,Visual C++,Timer,我想使用visual studio VC++2010类库使用两个计时器,一个用于读取传感器,另一个用于向机器人发出命令 如果单击按钮1,则第一个计时器打开,第二个计时器使用按钮3 但当我点击按钮2时,即使我没有按下按钮1,我的读取传感器仍在工作,反之亦然 这是我的节目: 我的代码有什么问题 const int cTimer1 = 1; const int cTimer2 = 1; void CENVSConfigDlg::OnBnClickedButton1() { SetTimer(cTi
const int cTimer1 = 1;
const int cTimer2 = 1;
void CENVSConfigDlg::OnBnClickedButton1()
{
SetTimer(cTimer1,1000,NULL);
}
void CENVSConfigDlg::OnBnClickedButton2()
{
KillTimer(cTimer1);
}
void CENVSConfigDlg::OnBnClickedButton3()
{
SetTimer(cTimer2,10,NULL);
}
void CENVSConfigDlg::OnBnClickedButton4()
{
KillTimer(cTimer2);
}
void CENVSConfigDlg::OnTimer(UINT_PTR ID){
if(ID==cTimer1){
char buffer[30],tempStr[5];
int sensor[6];
DWORD nbytes;
MessageBeep(0);
//Read Sensors
if(!WriteFile( hnd_serial, "1", 1, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Write Com Port fail!");return;}
Sleep(30);
if(!ReadFile( hnd_serial, buffer, 30, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Read Com Port fail!");return;}
Sleep(300);
if(ID==cTimer2)
{
if(GetAsyncKeyState(0x53) != 0)
{
DWORD nbytes;
if(!WriteFile( hnd_serial, "s", 1, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
Sleep(30);
tampil.SetWindowText( (LPCTSTR)"s" ); //backward
}
else if(GetAsyncKeyState(0x57) != 0)
{
DWORD nbytes;
if(!WriteFile( hnd_serial, "w", 1, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
Sleep(30);
tampil.SetWindowText( (LPCTSTR)"w" );//forward
}
}
}
}
幸好你发现了自己的错误。但是你的代码仍然有一些小故障
- 您正在计时器(
message)本身中执行读取、写入和睡眠。这将导致UI线程冻结。您最好使用另一个线程来处理,这涉及到UI更新以外的内容WM_timer
- 您的计时器ID的名称类似于
,Timer1
等,这对程序员不友好。你应该用更好的名字来反映实际的意思Timer2
- 多个计时器不能同时工作。同样,您最好使用多线程李>