gpt4 book ai didi

c++ - OnTimer 方法在 MFC 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:19 24 4
gpt4 key购买 nike

我在 VS2010 中创建了一个基于 MFC 对话框的应用程序,并希望添加计时器以每 3 秒更新一次图片 Controller 。但是 OnTimer 方法从未起作用。

我使用类向导将 WM_TIMER 添加到消息队列中,结果如下:

BEGIN_MESSAGE_MAP(CxxxxDlg, CDialogEx)
ON_WM_PAINT()
ON_BN_CLICKED(IDOK, &CxxxxDlg::OnBnClickedOK)
ON_WM_TIMER()
END_MESSAGE_MAP()

在 xxxxDlg.cpp 中,我将 SetTimer 方法放在 OnInitDialog 中:

BOOL CxxxxDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, TRUE);

_imageCounter = 1;
_isMale = 3;
_testNum = 0;

SetTimer(123, 2000, NULL);

bFullScreen = false;
OnFullShow();
updateImages();
UpdateData();

return TRUE;
}

在 xxxxdlv.h 中声明了 OnTimer 方法:

public:
afx_msg void OnTimer(UINT_PTR nIDEvent);

当我运行该应用程序时,SetTimer 返回 123。因此此处一切正常。 但是程序没有到达我在 OnTimer 方法第一行设置的断点!

然后我写了另一个hello world 项目来测试计时器。我以完全相同的方式设置计时器并且效果很好。

所以我认为 OnFullShow() 方法可能是问题所在。此方法用于将窗口更改为全屏模式。我评论了这一行,但 OnTimer 仍然没有工作。

我已经检查了问题here .但这没有帮助。

有谁知道问题出在哪里?谢谢!

附言。我确实收到了一些内存泄漏的警告。这重要吗?

最佳答案

感谢@IInspectable。我找到了技术支持here .它充分说明了原因并告诉了一种解决方案:

// Rewrite PreTranslateMessage method
BOOL CMyApp::PreTranslateMessage( MSG *pMsg )
{
// If this is a timer callback message let it pass on through to the
// DispatchMessage call.
if( (pMsg->message==WM_TIMER) && (pMsg->hwnd==NULL) )
return FALSE;
...
// The rest of your PreTranslateMessage goes here.
...

return CWinApp::PreTranslateMessage(pMsg);
}

这个解决方案并没有解决我的问题,但给了我一个提示。应重写 PreTranslateMessage 方法,让 WM_TIMER 传递给 DispatchMessage 调用。 但是如果你正在使用PreTranslateMessage来处理其他消息,例如WM_KEYDOWN,上述解决方案可能不起作用。好像是优先级的问题。最后,我使用 switch 而不是 if 解决了这个问题:

// Rewrite PreTranslateMessage method
BOOL CMyApp::PreTranslateMessage( MSG *pMsg )
{
// If this is a timer callback message let it pass on through to the
// DispatchMessage call.
switch(pMsg->message)
{
case WM_KEYDOWN: // your codes
case WM_TIMER: return false;
...
}
...
// The rest of your PreTranslateMessage goes here.
...

return CWinApp::PreTranslateMessage(pMsg);
}

希望对遇到类似问题的人有所帮助。

附言。 pMsg->hwnd==NULLswitch中被移除,我不确定是否安全。

关于c++ - OnTimer 方法在 MFC 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19217950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com