让MessageBox出现在窗口而非桌面中央

messageboxex.h文件

// -------------------------------------------------------------------------
namespace messsageboxex {
// -------------------------------------------------------------------------

int MessageBox( HWND hwnd, LPCTSTR szText, LPCTSTR szTitle, UINT uType );

// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------

messageboxex.cpp文件

#include // -------------------------------------------------------------------------
namespace messsageboxex {
// -------------------------------------------------------------------------


static LRESULT CALLBACK CbtHookProc( int, WPARAM, LPARAM );
LRESULT CALLBACK CustomMessageBoxProc( HWND, UINT, WPARAM, LPARAM );

struct CustomMessageBoxValues
{
   HHOOK hHook;
   HWND  hWnd;
   WNDPROC lpMsgBoxProc;
} static __declspec(thread) cmbv;

int MessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType )
{
   cmbv.hHook			= NULL;
   cmbv.hWnd			= NULL;
   cmbv.lpMsgBoxProc	= NULL;
 
   cmbv.hHook = ::SetWindowsHookEx( WH_CBT, CbtHookProc, NULL, GetCurrentThreadId() );

   int nRet = ::MessageBox( hWnd, lpText, lpCaption, uType );

   ::UnhookWindowsHookEx( cmbv.hHook );
   
   return nRet;
}

LRESULT CALLBACK CustomMessageBoxProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
   switch ( uMsg )
   {
   case WM_INITDIALOG:
      {
		  LRESULT lRet = ::CallWindowProc( cmbv.lpMsgBoxProc, hWnd, uMsg, wParam, lParam );
		  CWindow wnd( hWnd );
		  wnd.CenterWindow();		  
		  return lRet;
      }
      break;
   }

   return ::CallWindowProc(cmbv.lpMsgBoxProc, hWnd, uMsg, wParam, lParam);
}

LRESULT CALLBACK CbtHookProc( int nCode, WPARAM wParam, LPARAM lParam )
{
   if ( nCode < 0 )
       return ::CallNextHookEx(cmbv.hHook, nCode, wParam, lParam); 
   
   switch(nCode)
   {
   case HCBT_CREATEWND: 
      {
         LPCBT_CREATEWND lpCbtCreate = (LPCBT_CREATEWND)lParam;
         if ( WC_DIALOG == lpCbtCreate->lpcs->lpszClass )
         {
            // WC_DIALOG is the class name of message box
            // but it has not yet a window procedure set.
            // So keep in mind the handle to sublass it later
            // when its first child is about to be created
            cmbv.hWnd = (HWND)wParam;
         }
         else
         {
            if ( (NULL == cmbv.lpMsgBoxProc) && (NULL != cmbv.hWnd) )
            {
               // subclass the dialog 
               cmbv.lpMsgBoxProc = (WNDPROC)::SetWindowLong( cmbv.hWnd, GWL_WNDPROC, (LONG)CustomMessageBoxProc );
            }
         }
      }
      break; 
   }

   return ::CallNextHookEx(cmbv.hHook, nCode, wParam, lParam);
}


// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------

注意:需要WTL CWindow支持

你可能感兴趣的:(让MessageBox出现在窗口而非桌面中央)