OnTimer中加入MessageBox后 MessageBox一直不断弹出
BOOL CAlarmClockDlg::OnInitDialog()
{
……
SetTimer(1,1000,NULL);
……
}
void CAlarmClockDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
static int respons=1;
//do something
if(…… && respons)
{
MessageBox("时间到!");
respon=0;
}
CDialog::OnTimer(nIDEvent);
}
为啥我在这里加的respons没有起作用。到时间时,MessageBox竟一直不断弹出。请问我是哪里出毛病了?? MFC?? OnTimer MessageBox 消息映射
[解决办法]
调整一下:
if(…… && respons)
{
respon=0;
MessageBox("时间到!");
}
[解决办法]
因为messagebox可能导致OnTimer()函数退出,没有给respon赋值为0
[解决办法]
static int respons=1;
这个局部静态变量一开始是1,但是后来被你修改为0了,并且以后一直都是保持0值
你对程序的存储结构不是很理解,所以导致你以为再次进入OnTimer后response会重新赋值为1
但由于静态变量保存在堆内存中,而你的函数代码保存在栈中
函数部分每次执行的时候都是会被重新赋值的,但堆内存中的数据不会被清掉
[解决办法]
先理解消息循环的机制,你弹出MessageBox之后,MessageBox接管了消息的处理,屏蔽了对父窗口的一些消息,但是WM_TIMER消息是不屏蔽的,所以在MessageBox里面又进入到OnTimer这个函数中来,继续弹出MessageBox,如果你按1楼的把 respon = 0 放在MessageBox之前,就没问题了.