HWND g_hwndTimedOwner = 0;
BOOL g_bTimedOut = 0;
void CALLBACK MessageBoxTimer(HWND hwnd,
UINT uiMsg,
UINT idEvent,
DWORD dwTime)
{
g_bTimedOut = TRUE;
if (g_hwndTimedOwner)
EnableWindow(g_hwndTimedOwner, TRUE);
PostQuitMessage(0);
}
int TimedMessageBox(HWND hwndOwner,
LPCTSTR pszMessage,
LPCTSTR pszTitle,
UINT flags,
DWORD dwTimeout)
{
UINT idTimer;
int iResult;
g_hwndTimedOwner = NULL;
g_bTimedOut = FALSE;
if (hwndOwner && IsWindowEnabled(hwndOwner))
g_hwndTimedOwner = hwndOwner;
// Set a timer to dismiss the message box.
idTimer = SetTimer(NULL, 0, dwTimeout, (TIMERPROC)MessageBoxTimer);
iResult = MessageBox(hwndOwner, pszMessage, pszTitle, flags);
// Finished with the timer.
KillTimer(NULL, idTimer);
// See if there is a WM_QUIT message in the queue if we timed out.
// Eat the message so we do not quit the whole application.
if (g_bTimedOut)
{
MSG msg;
PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
iResult = -1;
}
return iResult;
BOOL g_bTimedOut = 0;
void CALLBACK MessageBoxTimer(HWND hwnd,
UINT uiMsg,
UINT idEvent,
DWORD dwTime)
{
g_bTimedOut = TRUE;
if (g_hwndTimedOwner)
EnableWindow(g_hwndTimedOwner, TRUE);
PostQuitMessage(0);
}
int TimedMessageBox(HWND hwndOwner,
LPCTSTR pszMessage,
LPCTSTR pszTitle,
UINT flags,
DWORD dwTimeout)
{
UINT idTimer;
int iResult;
g_hwndTimedOwner = NULL;
g_bTimedOut = FALSE;
if (hwndOwner && IsWindowEnabled(hwndOwner))
g_hwndTimedOwner = hwndOwner;
// Set a timer to dismiss the message box.
idTimer = SetTimer(NULL, 0, dwTimeout, (TIMERPROC)MessageBoxTimer);
iResult = MessageBox(hwndOwner, pszMessage, pszTitle, flags);
// Finished with the timer.
KillTimer(NULL, idTimer);
// See if there is a WM_QUIT message in the queue if we timed out.
// Eat the message so we do not quit the whole application.
if (g_bTimedOut)
{
MSG msg;
PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
iResult = -1;
}
return iResult;
}
用法:
TimedMessageBox( theApp.m_pMainWnd->m_hWnd, CString("设置2000毫秒显示,然后自动关闭"), _T("消息框标题"), MB_OK, 2000 );