1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
21 #pragma implementation "app.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
27 #if defined(__BORLANDC__)
35 #include "wx/gdicmn.h"
38 #include "wx/cursor.h"
40 #include "wx/palette.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
51 #include "wx/cmdline.h"
52 #include "wx/filename.h"
53 #include "wx/module.h"
55 #include "wx/msw/private.h"
58 #include "wx/thread.h"
60 // define the array of MSG strutures
61 WX_DECLARE_OBJARRAY(MSG
, wxMsgArray
);
63 #include "wx/arrimpl.cpp"
65 WX_DEFINE_OBJARRAY(wxMsgArray
);
66 #endif // wxUSE_THREADS
69 #include "wx/tooltip.h"
70 #endif // wxUSE_TOOLTIPS
72 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
73 // compilers don't support it (missing headers, libs, ...)
74 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
78 #endif // broken compilers
87 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
91 #ifndef __WXMICROWIN__
92 #include "wx/msw/msvcrt.h"
95 // ----------------------------------------------------------------------------
96 // conditional compilation
97 // ----------------------------------------------------------------------------
99 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
100 // defined before) and shows us what common control features are available
101 // during the compile time (it doesn't mean that they will be available during
102 // the run-time, use GetComCtl32Version() to test for them!). The possible
105 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
106 // 0x0300 4.70 IE 3.x
107 // 0x0400 4.71 IE 4.0
108 // 0x0401 4.72 IE 4.01 and Win98
109 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
112 // minimal set of features by default
113 #define _WIN32_IE 0x0200
116 #if _WIN32_IE >= 0x0300 && \
117 (!defined(__MINGW32__) || wxCHECK_W32API_VERSION( 2, 0 )) && \
122 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 extern wxChar
*wxBuffer
;
127 extern wxList WXDLLEXPORT wxPendingDelete
;
128 #ifndef __WXMICROWIN__
129 extern void wxSetKeyboardHook(bool doIt
);
133 wxApp
*wxTheApp
= NULL
;
135 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
136 // with NR suffix - wxWindow::MSWCreate() supposes this
137 const wxChar
*wxCanvasClassName
= wxT("wxWindowClass");
138 const wxChar
*wxCanvasClassNameNR
= wxT("wxWindowClassNR");
139 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
140 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
141 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
142 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
144 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
145 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
146 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
148 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
149 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
150 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
152 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
154 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
156 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
157 // needs compiler support for Win32 SEH. Others (especially Borland)
158 // probably have it too, but I'm not sure about how it works
159 // JACS: get 'Cannot use __try in functions that require unwinding
160 // in Unicode mode, so disabling.
161 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
162 #undef wxUSE_ON_FATAL_EXCEPTION
163 #define wxUSE_ON_FATAL_EXCEPTION 0
166 #if wxUSE_ON_FATAL_EXCEPTION
167 static bool gs_handleExceptions
= FALSE
;
170 // ===========================================================================
172 // ===========================================================================
174 // ---------------------------------------------------------------------------
176 // ---------------------------------------------------------------------------
178 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
180 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
181 EVT_IDLE(wxApp::OnIdle
)
182 EVT_END_SESSION(wxApp::OnEndSession
)
183 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
187 bool wxApp::Initialize()
189 // the first thing to do is to check if we're trying to run an Unicode
190 // program under Win9x w/o MSLU emulation layer - if so, abort right now
191 // as it has no chance to work
192 #if wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
193 if ( wxGetOsVersion() != wxWINDOWS_NT
)
195 // note that we can use MessageBoxW() as it's implemented even under
196 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
197 // used by wxLocale are not
201 _T("This program uses Unicode and requires Windows NT/2000/XP.\nProgram aborted."),
202 _T("wxWindows Fatal Error"),
208 #endif // wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
210 wxBuffer
= new wxChar
[1500]; // FIXME
212 wxClassInfo::InitializeClasses();
215 wxPendingEventsLocker
= new wxCriticalSection
;
218 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
219 wxTheColourDatabase
->Initialize();
221 wxInitializeStockLists();
222 wxInitializeStockObjects();
224 wxBitmap::InitStandardHandlers();
226 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
227 InitCommonControls();
230 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
233 // for OLE, enlarge message queue to be as large as possible
235 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
240 // we need to initialize OLE library
241 if ( FAILED(::OleInitialize(NULL
)) )
242 wxLogError(_("Cannot initialize OLE"));
248 if (!Ctl3dRegister(wxhInstance
))
249 wxLogError(wxT("Cannot register CTL3D"));
251 Ctl3dAutoSubclass(wxhInstance
);
252 #endif // wxUSE_CTL3D
254 // VZ: these icons are not in wx.rc anyhow (but should they?)!
256 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
257 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
258 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
260 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
261 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
262 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
265 RegisterWindowClasses();
267 #ifndef __WXMICROWIN__
268 // Create the brush for disabling bitmap buttons
271 lb
.lbStyle
= BS_PATTERN
;
273 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
276 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
277 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
279 //else: wxWindows resources are probably not linked in
286 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
288 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
289 // PLEASE DO NOT ALTER THIS.
290 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
291 extern char wxDummyChar
;
292 if (wxDummyChar
) wxDummyChar
++;
295 #ifndef __WXMICROWIN__
296 wxSetKeyboardHook(TRUE
);
299 wxModule::RegisterModules();
300 if (!wxModule::InitializeModules())
305 // ---------------------------------------------------------------------------
306 // RegisterWindowClasses
307 // ---------------------------------------------------------------------------
309 // TODO we should only register classes really used by the app. For this it
310 // would be enough to just delay the class registration until an attempt
311 // to create a window of this class is made.
312 bool wxApp::RegisterWindowClasses()
315 wxZeroMemory(wndclass
);
317 // for each class we register one with CS_(V|H)REDRAW style and one
318 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
319 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
320 static const long styleNoRedraw
= CS_DBLCLKS
;
322 // the fields which are common to all classes
323 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
324 wndclass
.hInstance
= wxhInstance
;
325 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
327 // Register the frame window class.
328 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
329 wndclass
.lpszClassName
= wxCanvasClassName
;
330 wndclass
.style
= styleNormal
;
332 if ( !RegisterClass(&wndclass
) )
334 wxLogLastError(wxT("RegisterClass(frame)"));
338 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
339 wndclass
.style
= styleNoRedraw
;
341 if ( !RegisterClass(&wndclass
) )
343 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
346 // Register the MDI frame window class.
347 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
348 wndclass
.lpszClassName
= wxMDIFrameClassName
;
349 wndclass
.style
= styleNormal
;
351 if ( !RegisterClass(&wndclass
) )
353 wxLogLastError(wxT("RegisterClass(MDI parent)"));
356 // "no redraw" MDI frame
357 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
358 wndclass
.style
= styleNoRedraw
;
360 if ( !RegisterClass(&wndclass
) )
362 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
365 // Register the MDI child frame window class.
366 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
367 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
368 wndclass
.style
= styleNormal
;
370 if ( !RegisterClass(&wndclass
) )
372 wxLogLastError(wxT("RegisterClass(MDI child)"));
375 // "no redraw" MDI child frame
376 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
377 wndclass
.style
= styleNoRedraw
;
379 if ( !RegisterClass(&wndclass
) )
381 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
387 // ---------------------------------------------------------------------------
388 // UnregisterWindowClasses
389 // ---------------------------------------------------------------------------
391 bool wxApp::UnregisterWindowClasses()
395 #ifndef __WXMICROWIN__
396 // MDI frame window class.
397 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
399 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
404 // "no redraw" MDI frame
405 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
407 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
412 // MDI child frame window class.
413 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
415 wxLogLastError(wxT("UnregisterClass(MDI child)"));
420 // "no redraw" MDI child frame
421 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
423 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
429 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
431 wxLogLastError(wxT("UnregisterClass(canvas)"));
436 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
438 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
442 #endif // __WXMICROWIN__
447 // ---------------------------------------------------------------------------
448 // Convert Windows to argc, argv style
449 // ---------------------------------------------------------------------------
451 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
453 // break the command line in words
455 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
457 // +1 here for the program name
458 argc
= args
.GetCount() + 1;
460 // and +1 here for the terminating NULL
461 argv
= new wxChar
*[argc
+ 1];
463 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
464 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
466 // also set the app name from argv[0]
468 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
470 // but don't override the name already set by the user code, if any
471 if ( GetAppName().empty() )
474 // copy all the other arguments to wxApp::argv[]
475 for ( int i
= 1; i
< argc
; i
++ )
477 argv
[i
] = copystring(args
[i
- 1]);
480 // argv[] must be NULL-terminated
484 //// Cleans up any wxWindows internal structures left lying around
486 void wxApp::CleanUp()
491 // flush the logged messages if any and install a 'safer' log target: the
492 // default one (wxLogGui) can't be used after the resources are freed just
493 // below and the user suppliedo ne might be even more unsafe (using any
494 // wxWindows GUI function is unsafe starting from now)
495 wxLog::DontCreateOnDemand();
497 // this will flush the old messages if any
498 delete wxLog::SetActiveTarget(new wxLogStderr
);
501 // One last chance for pending objects to be cleaned up
502 wxTheApp
->DeletePendingObjects();
504 wxModule::CleanUpModules();
506 wxDeleteStockObjects();
508 // Destroy all GDI lists, etc.
509 wxDeleteStockLists();
511 delete wxTheColourDatabase
;
512 wxTheColourDatabase
= NULL
;
514 wxBitmap::CleanUpHandlers();
519 //// WINDOWS-SPECIFIC CLEANUP
521 #ifndef __WXMICROWIN__
522 wxSetKeyboardHook(FALSE
);
529 if (wxSTD_FRAME_ICON
)
530 DestroyIcon(wxSTD_FRAME_ICON
);
531 if (wxSTD_MDICHILDFRAME_ICON
)
532 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
533 if (wxSTD_MDIPARENTFRAME_ICON
)
534 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
536 if (wxDEFAULT_FRAME_ICON
)
537 DestroyIcon(wxDEFAULT_FRAME_ICON
);
538 if (wxDEFAULT_MDICHILDFRAME_ICON
)
539 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
540 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
541 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
543 if ( wxDisableButtonBrush
)
544 ::DeleteObject( wxDisableButtonBrush
);
551 // for an EXE the classes are unregistered when it terminates but DLL may
552 // be loaded several times (load/unload/load) into the same process in
553 // which case the registration will fail after the first time if we don't
554 // unregister the classes now
555 UnregisterWindowClasses();
556 #endif // WXMAKINGDLL
559 Ctl3dUnregister(wxhInstance
);
562 delete wxWinHandleHash
;
563 wxWinHandleHash
= NULL
; // Set to null in case anything later tries to ref it.
565 delete wxPendingEvents
;
566 wxPendingEvents
= NULL
; // Set to null because wxAppBase::wxEvtHandler is destroyed later.
569 delete wxPendingEventsLocker
;
570 wxPendingEventsLocker
= NULL
; // Set to null because wxAppBase::wxEvtHandler is destroyed later.
571 // If we don't do the following, we get an apparent memory leak
573 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
574 #endif // wxUSE_VALIDATORS
575 #endif // wxUSE_THREADS
577 wxClassInfo::CleanUpClasses();
582 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
583 // At this point we want to check if there are any memory
584 // blocks that aren't part of the wxDebugContext itself,
585 // as a special case. Then when dumping we need to ignore
586 // wxDebugContext, too.
587 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
589 wxLogMessage(wxT("There were memory leaks."));
590 wxDebugContext::Dump();
591 wxDebugContext::PrintStatistics();
593 // wxDebugContext::SetStream(NULL, NULL);
597 // do it as the very last thing because everything else can log messages
598 delete wxLog::SetActiveTarget(NULL
);
602 //----------------------------------------------------------------------
603 // Entry point helpers, used by wxPython
604 //----------------------------------------------------------------------
606 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
608 return wxApp::Initialize();
611 int WXDLLEXPORT
wxEntryInitGui()
613 return wxTheApp
->OnInitGui();
616 void WXDLLEXPORT
wxEntryCleanup()
622 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
624 // temporarily disable this warning which would be generated in release builds
627 #pragma warning(disable: 4715) // not all control paths return a value
630 //----------------------------------------------------------------------
631 // Main wxWindows entry point
632 //----------------------------------------------------------------------
633 int wxEntry(WXHINSTANCE hInstance
,
634 WXHINSTANCE
WXUNUSED(hPrevInstance
),
639 // do check for memory leaks on program exit
640 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
641 // deallocated memory which may be used to simulate low-memory condition)
642 #ifndef __WXMICROWIN__
643 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
647 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
648 // This seems to be necessary since there are 'rogue'
649 // objects present at this point (perhaps global objects?)
650 // Setting a checkpoint will ignore them as far as the
651 // memory checking facility is concerned.
652 // Of course you may argue that memory allocated in globals should be
653 // checked, but this is a reasonable compromise.
654 wxDebugContext::SetCheckpoint();
658 // take everything into a try-except block to be able to call
659 // OnFatalException() if necessary
660 #if wxUSE_ON_FATAL_EXCEPTION
663 wxhInstance
= (HINSTANCE
) hInstance
;
665 if (!wxEntryStart(0,0))
668 // create the application object or ensure that one already exists
671 // The app may have declared a global application object, but we recommend
672 // the IMPLEMENT_APP macro is used instead, which sets an initializer
673 // function for delayed, dynamic app object construction.
674 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
675 wxT("No initializer - use IMPLEMENT_APP macro.") );
677 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
680 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
682 // save the WinMain() parameters
683 if (lpCmdLine
) // MicroWindows passes NULL
684 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
685 wxTheApp
->m_nCmdShow
= nCmdShow
;
687 // We really don't want timestamps by default, because it means
688 // we can't simply double-click on the error message and get to that
689 // line in the source. So VC++ at least, let's have a sensible default.
692 wxLog::SetTimestamp(NULL
);
694 #endif // __VISUALC__
697 int retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
708 // we want to initialize, but not run or exit immediately.
712 //else: app initialization failed, so we skipped OnRun()
714 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
717 // Forcibly delete the window.
718 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
719 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
721 topWindow
->Close(TRUE
);
722 wxTheApp
->DeletePendingObjects();
727 wxTheApp
->SetTopWindow(NULL
);
731 retValue
= wxTheApp
->OnExit();
737 #if wxUSE_ON_FATAL_EXCEPTION
739 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
740 : EXCEPTION_CONTINUE_SEARCH
) {
743 // give the user a chance to do something special about this
744 wxTheApp
->OnFatalException();
747 ::ExitProcess(3); // the same exit code as abort()
751 #endif // wxUSE_ON_FATAL_EXCEPTION
754 // restore warning state
756 #pragma warning(default: 4715) // not all control paths return a value
761 //----------------------------------------------------------------------
762 // Entry point for wxWindows + the App in a DLL
763 //----------------------------------------------------------------------
765 int wxEntry(WXHINSTANCE hInstance
)
767 wxhInstance
= (HINSTANCE
) hInstance
;
770 // The app may have declared a global application object, but we recommend
771 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
772 // for delayed, dynamic app object construction.
775 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
776 "No initializer - use IMPLEMENT_APP macro." );
778 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
781 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
784 wxTheApp
->argv
= NULL
;
790 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
791 if ( topWindow
&& topWindow
->GetHWND())
793 topWindow
->Show(TRUE
);
800 //// Static member initialization
802 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
808 m_printMode
= wxPRINT_WINDOWS
;
814 // Delete command-line args
816 for (i
= 0; i
< argc
; i
++)
823 bool wxApp::Initialized()
830 #else // Assume initialized if DLL (no way of telling)
836 * Get and process a message, returning FALSE if WM_QUIT
837 * received (and also set the flag telling the app to exit the main loop)
840 bool wxApp::DoMessage()
842 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
852 // should never happen, but let's test for it nevertheless
853 wxLogLastError(wxT("GetMessage"));
858 wxASSERT_MSG( wxThread::IsMain(),
859 wxT("only the main thread can process Windows messages") );
861 static bool s_hadGuiLock
= TRUE
;
862 static wxMsgArray s_aSavedMessages
;
864 // if a secondary thread owns is doing GUI calls, save all messages for
865 // later processing - we can't process them right now because it will
866 // lead to recursive library calls (and we're not reentrant)
867 if ( !wxGuiOwnedByMainThread() )
869 s_hadGuiLock
= FALSE
;
871 // leave out WM_COMMAND messages: too dangerous, sometimes
872 // the message will be processed twice
873 if ( !wxIsWaitingForThread() ||
874 s_currentMsg
.message
!= WM_COMMAND
)
876 s_aSavedMessages
.Add(s_currentMsg
);
883 // have we just regained the GUI lock? if so, post all of the saved
886 // FIXME of course, it's not _exactly_ the same as processing the
887 // messages normally - expect some things to break...
892 size_t count
= s_aSavedMessages
.GetCount();
893 for ( size_t n
= 0; n
< count
; n
++ )
895 MSG
& msg
= s_aSavedMessages
[n
];
897 DoMessage((WXMSG
*)&msg
);
900 s_aSavedMessages
.Empty();
903 #endif // wxUSE_THREADS
905 // Process the message
906 DoMessage((WXMSG
*)&s_currentMsg
);
912 void wxApp::DoMessage(WXMSG
*pMsg
)
914 if ( !ProcessMessage(pMsg
) )
916 ::TranslateMessage((MSG
*)pMsg
);
917 ::DispatchMessage((MSG
*)pMsg
);
922 * Keep trying to process messages until WM_QUIT
925 * If there are messages to be processed, they will all be
926 * processed and OnIdle will not be called.
927 * When there are no more messages, OnIdle is called.
928 * If OnIdle requests more time,
929 * it will be repeatedly called so long as there are no pending messages.
930 * A 'feature' of this is that once OnIdle has decided that no more processing
931 * is required, then it won't get processing time until further messages
932 * are processed (it'll sit in DoMessage).
935 int wxApp::MainLoop()
939 while ( m_keepGoing
)
942 wxMutexGuiLeaveOrEnter();
943 #endif // wxUSE_THREADS
945 while ( !Pending() && ProcessIdle() )
948 // a message came or no more idle processing to do
952 return s_currentMsg
.wParam
;
955 // Returns TRUE if more time is needed.
956 bool wxApp::ProcessIdle()
959 event
.SetEventObject(this);
962 return event
.MoreRequested();
965 void wxApp::ExitMainLoop()
967 // this will set m_keepGoing to FALSE a bit later
968 ::PostQuitMessage(0);
971 bool wxApp::Pending()
973 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
976 void wxApp::Dispatch()
982 * Give all windows a chance to preprocess
983 * the message. Some may have accelerator tables, or have
987 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
989 MSG
*msg
= (MSG
*)wxmsg
;
990 HWND hwnd
= msg
->hwnd
;
991 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
993 // this may happen if the event occured in a standard modeless dialog (the
994 // only example of which I know of is the find/replace dialog) - then call
995 // IsDialogMessage() to make TAB navigation in it work
998 // we need to find the dialog containing this control as
999 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1000 // them) if we call it for the control itself
1001 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1003 hwnd
= ::GetParent(hwnd
);
1006 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1010 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1011 // popup the tooltip bubbles
1012 if ( (msg
->message
== WM_MOUSEMOVE
) )
1014 wxToolTip
*tt
= wndThis
->GetToolTip();
1017 tt
->RelayEvent(wxmsg
);
1020 #endif // wxUSE_TOOLTIPS
1022 // allow the window to prevent certain messages from being
1023 // translated/processed (this is currently used by wxTextCtrl to always
1024 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1025 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1030 // try translations first: the accelerators override everything
1033 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1035 if ( wnd
->MSWTranslateMessage(wxmsg
))
1038 // stop at first top level window, i.e. don't try to process the key
1039 // strokes originating in a dialog using the accelerators of the parent
1040 // frame - this doesn't make much sense
1041 if ( wnd
->IsTopLevel() )
1045 // now try the other hooks (kbd navigation is handled here): we start from
1046 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1048 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1050 if ( wnd
->MSWProcessMessage(wxmsg
) )
1054 // no special preprocessing for this message, dispatch it normally
1058 // this is a temporary hack and will be replaced by using wxEventLoop in the
1061 // it is needed to allow other event loops (currently only one: the modal
1062 // dialog one) to reset the OnIdle() semaphore because otherwise OnIdle()
1063 // wouldn't do anything while a modal dialog shown from OnIdle() call is shown.
1064 bool wxIsInOnIdleFlag
= FALSE
;
1066 void wxApp::OnIdle(wxIdleEvent
& event
)
1068 // Avoid recursion (via ProcessEvent default case)
1069 if ( wxIsInOnIdleFlag
)
1072 wxIsInOnIdleFlag
= TRUE
;
1074 // If there are pending events, we must process them: pending events
1075 // are either events to the threads other than main or events posted
1076 // with wxPostEvent() functions
1077 // GRG: I have moved this here so that all pending events are processed
1078 // before starting to delete any objects. This behaves better (in
1079 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1080 // behaviour. Changed Feb/2000 before 2.1.14
1081 ProcessPendingEvents();
1083 // 'Garbage' collection of windows deleted with Close().
1084 DeletePendingObjects();
1087 // flush the logged messages if any
1088 wxLog::FlushActive();
1091 #if wxUSE_DC_CACHEING
1092 // automated DC cache management: clear the cached DCs and bitmap
1093 // if it's likely that the app has finished with them, that is, we
1094 // get an idle event and we're not dragging anything.
1095 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1097 #endif // wxUSE_DC_CACHEING
1099 // Send OnIdle events to all windows
1100 if ( SendIdleEvents() )
1102 // SendIdleEvents() returns TRUE if at least one window requested more
1104 event
.RequestMore(TRUE
);
1107 wxIsInOnIdleFlag
= FALSE
;
1110 // Send idle event to all top-level windows
1111 bool wxApp::SendIdleEvents()
1113 bool needMore
= FALSE
;
1115 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1118 wxWindow
* win
= node
->GetData();
1119 if (SendIdleEvents(win
))
1121 node
= node
->GetNext();
1127 // Send idle event to window and all subwindows
1128 bool wxApp::SendIdleEvents(wxWindow
* win
)
1131 event
.SetEventObject(win
);
1132 win
->GetEventHandler()->ProcessEvent(event
);
1134 bool needMore
= event
.MoreRequested();
1136 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
1139 wxWindow
*win
= node
->GetData();
1140 if (SendIdleEvents(win
))
1143 node
= node
->GetNext();
1149 void wxApp::DeletePendingObjects()
1151 wxNode
*node
= wxPendingDelete
.GetFirst();
1154 wxObject
*obj
= node
->GetData();
1158 if (wxPendingDelete
.Member(obj
))
1161 // Deleting one object may have deleted other pending
1162 // objects, so start from beginning of list again.
1163 node
= wxPendingDelete
.GetFirst();
1167 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1170 GetTopWindow()->Close(TRUE
);
1173 // Default behaviour: close the application with prompts. The
1174 // user can veto the close, and therefore the end session.
1175 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1179 if (!GetTopWindow()->Close(!event
.CanVeto()))
1185 int wxApp::GetComCtl32Version()
1187 #ifdef __WXMICROWIN__
1191 static int s_verComCtl32
= -1;
1193 wxCRIT_SECT_DECLARE(csComCtl32
);
1194 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1196 if ( s_verComCtl32
== -1 )
1198 // initally assume no comctl32.dll at all
1202 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1204 // if so, then we can check for the version
1205 if ( hModuleComCtl32
)
1207 // try to use DllGetVersion() if available in _headers_
1208 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1209 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1210 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1211 if ( pfnDllGetVersion
)
1214 dvi
.cbSize
= sizeof(dvi
);
1216 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1219 wxLogApiError(_T("DllGetVersion"), hr
);
1223 // this is incompatible with _WIN32_IE values, but
1224 // compatible with the other values returned by
1225 // GetComCtl32Version()
1226 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1231 // DllGetVersion() unavailable either during compile or
1232 // run-time, try to guess the version otherwise
1233 if ( !s_verComCtl32
)
1235 // InitCommonControlsEx is unique to 4.70 and later
1236 FARPROC theProc
= ::GetProcAddress
1239 "InitCommonControlsEx"
1244 // not found, must be 4.00
1245 s_verComCtl32
= 400;
1249 // many symbols appeared in comctl32 4.71, could use
1250 // any of them except may be DllInstall
1251 theProc
= ::GetProcAddress
1258 // not found, must be 4.70
1259 s_verComCtl32
= 470;
1263 // found, must be 4.71
1264 s_verComCtl32
= 471;
1271 return s_verComCtl32
;
1279 wxTheApp
->ExitMainLoop();
1283 // what else can we do?
1288 // Yield to incoming messages
1290 bool wxApp::Yield(bool onlyIfNeeded
)
1293 static bool s_inYield
= FALSE
;
1296 // disable log flushing from here because a call to wxYield() shouldn't
1297 // normally result in message boxes popping up &c
1303 if ( !onlyIfNeeded
)
1305 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1313 // we don't want to process WM_QUIT from here - it should be processed in
1314 // the main event loop in order to stop it
1316 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1317 msg
.message
!= WM_QUIT
)
1320 wxMutexGuiLeaveOrEnter();
1321 #endif // wxUSE_THREADS
1323 if ( !wxTheApp
->DoMessage() )
1327 // if there are pending events, we must process them.
1328 ProcessPendingEvents();
1331 // let the logs be flashed again
1340 bool wxHandleFatalExceptions(bool doit
)
1342 #if wxUSE_ON_FATAL_EXCEPTION
1343 // assume this can only be called from the main thread
1344 gs_handleExceptions
= doit
;
1348 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1355 //-----------------------------------------------------------------------------
1357 //-----------------------------------------------------------------------------
1361 // Send the top window a dummy message so idle handler processing will
1362 // start up again. Doing it this way ensures that the idle handler
1363 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1364 // the same for the main app thread only)
1365 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1368 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1370 // should never happen
1371 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1376 //-----------------------------------------------------------------------------
1378 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1379 // if in a separate file. So include it here to ensure it's linked.
1380 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__WINE__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))