1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
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
68 #if wxUSE_WX_RESOURCES
69 #include "wx/resource.h"
73 #include "wx/tooltip.h"
74 #endif // wxUSE_TOOLTIPS
76 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
77 // compilers don't support it (missing headers, libs, ...)
78 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
82 #endif // broken compilers
91 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
95 #ifndef __WXMICROWIN__
96 #include "wx/msw/msvcrt.h"
99 // ----------------------------------------------------------------------------
100 // conditional compilation
101 // ----------------------------------------------------------------------------
103 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
104 // defined before) and shows us what common control features are available
105 // during the compile time (it doesn't mean that they will be available during
106 // the run-time, use GetComCtl32Version() to test for them!). The possible
109 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
110 // 0x0300 4.70 IE 3.x
111 // 0x0400 4.71 IE 4.0
112 // 0x0401 4.72 IE 4.01 and Win98
113 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
116 // minimal set of features by default
117 #define _WIN32_IE 0x0200
120 #if _WIN32_IE >= 0x0300 && \
121 (!defined(__MINGW32__) || wxCHECK_W32API_VERSION( 2, 0 ))
125 // ---------------------------------------------------------------------------
127 // ---------------------------------------------------------------------------
129 extern wxChar
*wxBuffer
;
130 extern wxList WXDLLEXPORT wxPendingDelete
;
131 #ifndef __WXMICROWIN__
132 extern void wxSetKeyboardHook(bool doIt
);
136 wxApp
*wxTheApp
= NULL
;
138 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
139 // with NR suffix - wxWindow::MSWCreate() supposes this
140 const wxChar
*wxCanvasClassName
= wxT("wxWindowClass");
141 const wxChar
*wxCanvasClassNameNR
= wxT("wxWindowClassNR");
142 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
143 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
144 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
145 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
147 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
148 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
149 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
151 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
152 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
153 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
155 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
157 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
159 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
160 // needs compiler support for Win32 SEH. Others (especially Borland)
161 // probably have it too, but I'm not sure about how it works
162 // JACS: get 'Cannot use __try in functions that require unwinding
163 // in Unicode mode, so disabling.
164 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
165 #undef wxUSE_ON_FATAL_EXCEPTION
166 #define wxUSE_ON_FATAL_EXCEPTION 0
169 #if wxUSE_ON_FATAL_EXCEPTION
170 static bool gs_handleExceptions
= FALSE
;
173 // ===========================================================================
175 // ===========================================================================
177 // ---------------------------------------------------------------------------
179 // ---------------------------------------------------------------------------
181 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
183 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
184 EVT_IDLE(wxApp::OnIdle
)
185 EVT_END_SESSION(wxApp::OnEndSession
)
186 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
190 bool wxApp::Initialize()
192 // the first thing to do is to check if we're trying to run an Unicode
193 // program under Win9x w/o MSLU emulation layer - if so, abort right now
194 // as it has no chance to work
195 #if wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
196 if ( wxGetOsVersion() != wxWINDOWS_NT
)
198 // note that we can use MessageBoxW() as it's implemented even under
199 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
200 // used by wxLocale are not
204 _T("This program uses Unicode and requires Windows NT/2000/XP.\nProgram aborted."),
205 _T("wxWindows Fatal Error"),
211 #endif // wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
213 wxBuffer
= new wxChar
[1500]; // FIXME
215 wxClassInfo::InitializeClasses();
218 wxPendingEventsLocker
= new wxCriticalSection
;
221 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
222 wxTheColourDatabase
->Initialize();
224 wxInitializeStockLists();
225 wxInitializeStockObjects();
227 #if wxUSE_WX_RESOURCES
228 wxInitializeResourceSystem();
231 wxBitmap::InitStandardHandlers();
233 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
234 InitCommonControls();
237 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
240 // for OLE, enlarge message queue to be as large as possible
242 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
247 // we need to initialize OLE library
248 if ( FAILED(::OleInitialize(NULL
)) )
249 wxLogError(_("Cannot initialize OLE"));
255 if (!Ctl3dRegister(wxhInstance
))
256 wxLogError(wxT("Cannot register CTL3D"));
258 Ctl3dAutoSubclass(wxhInstance
);
259 #endif // wxUSE_CTL3D
261 // VZ: these icons are not in wx.rc anyhow (but should they?)!
263 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
264 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
265 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
267 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
268 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
269 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
272 RegisterWindowClasses();
274 #ifndef __WXMICROWIN__
275 // Create the brush for disabling bitmap buttons
278 lb
.lbStyle
= BS_PATTERN
;
280 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
283 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
284 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
286 //else: wxWindows resources are probably not linked in
293 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
295 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
296 // PLEASE DO NOT ALTER THIS.
297 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
298 extern char wxDummyChar
;
299 if (wxDummyChar
) wxDummyChar
++;
302 #ifndef __WXMICROWIN__
303 wxSetKeyboardHook(TRUE
);
306 wxModule::RegisterModules();
307 if (!wxModule::InitializeModules())
312 // ---------------------------------------------------------------------------
313 // RegisterWindowClasses
314 // ---------------------------------------------------------------------------
316 // TODO we should only register classes really used by the app. For this it
317 // would be enough to just delay the class registration until an attempt
318 // to create a window of this class is made.
319 bool wxApp::RegisterWindowClasses()
322 wxZeroMemory(wndclass
);
324 // for each class we register one with CS_(V|H)REDRAW style and one
325 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
326 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
327 static const long styleNoRedraw
= CS_DBLCLKS
;
329 // the fields which are common to all classes
330 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
331 wndclass
.hInstance
= wxhInstance
;
332 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
334 // Register the frame window class.
335 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
336 wndclass
.lpszClassName
= wxCanvasClassName
;
337 wndclass
.style
= styleNormal
;
339 if ( !RegisterClass(&wndclass
) )
341 wxLogLastError(wxT("RegisterClass(frame)"));
345 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
346 wndclass
.style
= styleNoRedraw
;
348 if ( !RegisterClass(&wndclass
) )
350 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
353 // Register the MDI frame window class.
354 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
355 wndclass
.lpszClassName
= wxMDIFrameClassName
;
356 wndclass
.style
= styleNormal
;
358 if ( !RegisterClass(&wndclass
) )
360 wxLogLastError(wxT("RegisterClass(MDI parent)"));
363 // "no redraw" MDI frame
364 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
365 wndclass
.style
= styleNoRedraw
;
367 if ( !RegisterClass(&wndclass
) )
369 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
372 // Register the MDI child frame window class.
373 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
374 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
375 wndclass
.style
= styleNormal
;
377 if ( !RegisterClass(&wndclass
) )
379 wxLogLastError(wxT("RegisterClass(MDI child)"));
382 // "no redraw" MDI child frame
383 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
384 wndclass
.style
= styleNoRedraw
;
386 if ( !RegisterClass(&wndclass
) )
388 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
394 // ---------------------------------------------------------------------------
395 // UnregisterWindowClasses
396 // ---------------------------------------------------------------------------
398 bool wxApp::UnregisterWindowClasses()
402 #ifndef __WXMICROWIN__
403 // MDI frame window class.
404 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
406 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
411 // "no redraw" MDI frame
412 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
414 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
419 // MDI child frame window class.
420 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
422 wxLogLastError(wxT("UnregisterClass(MDI child)"));
427 // "no redraw" MDI child frame
428 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
430 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
436 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
438 wxLogLastError(wxT("UnregisterClass(canvas)"));
443 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
445 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
449 #endif // __WXMICROWIN__
454 // ---------------------------------------------------------------------------
455 // Convert Windows to argc, argv style
456 // ---------------------------------------------------------------------------
458 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
460 // break the command line in words
462 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
464 // +1 here for the program name
465 argc
= args
.GetCount() + 1;
467 // and +1 here for the terminating NULL
468 argv
= new wxChar
*[argc
+ 1];
470 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
471 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
473 // also set the app name from argv[0]
475 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
477 // but don't override the name already set by the user code, if any
478 if ( GetAppName().empty() )
481 // copy all the other arguments to wxApp::argv[]
482 for ( int i
= 1; i
< argc
; i
++ )
484 argv
[i
] = copystring(args
[i
- 1]);
487 // argv[] must be NULL-terminated
491 //// Cleans up any wxWindows internal structures left lying around
493 void wxApp::CleanUp()
498 // flush the logged messages if any and install a 'safer' log target: the
499 // default one (wxLogGui) can't be used after the resources are freed just
500 // below and the user suppliedo ne might be even more unsafe (using any
501 // wxWindows GUI function is unsafe starting from now)
502 wxLog::DontCreateOnDemand();
504 // this will flush the old messages if any
505 delete wxLog::SetActiveTarget(new wxLogStderr
);
508 // One last chance for pending objects to be cleaned up
509 wxTheApp
->DeletePendingObjects();
511 wxModule::CleanUpModules();
513 #if wxUSE_WX_RESOURCES
514 wxCleanUpResourceSystem();
516 // wxDefaultResourceTable->ClearTable();
519 wxDeleteStockObjects();
521 // Destroy all GDI lists, etc.
522 wxDeleteStockLists();
524 delete wxTheColourDatabase
;
525 wxTheColourDatabase
= NULL
;
527 wxBitmap::CleanUpHandlers();
532 //// WINDOWS-SPECIFIC CLEANUP
534 #ifndef __WXMICROWIN__
535 wxSetKeyboardHook(FALSE
);
542 if (wxSTD_FRAME_ICON
)
543 DestroyIcon(wxSTD_FRAME_ICON
);
544 if (wxSTD_MDICHILDFRAME_ICON
)
545 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
546 if (wxSTD_MDIPARENTFRAME_ICON
)
547 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
549 if (wxDEFAULT_FRAME_ICON
)
550 DestroyIcon(wxDEFAULT_FRAME_ICON
);
551 if (wxDEFAULT_MDICHILDFRAME_ICON
)
552 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
553 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
554 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
556 if ( wxDisableButtonBrush
)
557 ::DeleteObject( wxDisableButtonBrush
);
564 // for an EXE the classes are unregistered when it terminates but DLL may
565 // be loaded several times (load/unload/load) into the same process in
566 // which case the registration will fail after the first time if we don't
567 // unregister the classes now
568 UnregisterWindowClasses();
569 #endif // WXMAKINGDLL
572 Ctl3dUnregister(wxhInstance
);
575 delete wxWinHandleHash
;
577 // GL: I'm annoyed ... I don't know where to put this and I don't want to
578 // create a module for that as it's part of the core.
579 delete wxPendingEvents
;
582 delete wxPendingEventsLocker
;
583 // If we don't do the following, we get an apparent memory leak
585 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
586 #endif // wxUSE_VALIDATORS
587 #endif // wxUSE_THREADS
589 wxClassInfo::CleanUpClasses();
594 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
595 // At this point we want to check if there are any memory
596 // blocks that aren't part of the wxDebugContext itself,
597 // as a special case. Then when dumping we need to ignore
598 // wxDebugContext, too.
599 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
601 wxLogMessage(wxT("There were memory leaks."));
602 wxDebugContext::Dump();
603 wxDebugContext::PrintStatistics();
605 // wxDebugContext::SetStream(NULL, NULL);
609 // do it as the very last thing because everything else can log messages
610 delete wxLog::SetActiveTarget(NULL
);
614 //----------------------------------------------------------------------
615 // Entry point helpers, used by wxPython
616 //----------------------------------------------------------------------
618 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
620 return wxApp::Initialize();
623 int WXDLLEXPORT
wxEntryInitGui()
625 return wxTheApp
->OnInitGui();
628 void WXDLLEXPORT
wxEntryCleanup()
634 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
636 // temporarily disable this warning which would be generated in release builds
639 #pragma warning(disable: 4715) // not all control paths return a value
642 //----------------------------------------------------------------------
643 // Main wxWindows entry point
644 //----------------------------------------------------------------------
645 int wxEntry(WXHINSTANCE hInstance
,
646 WXHINSTANCE
WXUNUSED(hPrevInstance
),
651 // do check for memory leaks on program exit
652 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
653 // deallocated memory which may be used to simulate low-memory condition)
654 #ifndef __WXMICROWIN__
655 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
659 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
660 // This seems to be necessary since there are 'rogue'
661 // objects present at this point (perhaps global objects?)
662 // Setting a checkpoint will ignore them as far as the
663 // memory checking facility is concerned.
664 // Of course you may argue that memory allocated in globals should be
665 // checked, but this is a reasonable compromise.
666 wxDebugContext::SetCheckpoint();
670 // take everything into a try-except block to be able to call
671 // OnFatalException() if necessary
672 #if wxUSE_ON_FATAL_EXCEPTION
675 wxhInstance
= (HINSTANCE
) hInstance
;
677 if (!wxEntryStart(0,0))
680 // create the application object or ensure that one already exists
683 // The app may have declared a global application object, but we recommend
684 // the IMPLEMENT_APP macro is used instead, which sets an initializer
685 // function for delayed, dynamic app object construction.
686 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
687 wxT("No initializer - use IMPLEMENT_APP macro.") );
689 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
692 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
694 // save the WinMain() parameters
695 if (lpCmdLine
) // MicroWindows passes NULL
696 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
697 wxTheApp
->m_nCmdShow
= nCmdShow
;
699 // We really don't want timestamps by default, because it means
700 // we can't simply double-click on the error message and get to that
701 // line in the source. So VC++ at least, let's have a sensible default.
703 wxLog::SetTimestamp(NULL
);
707 int retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
714 retValue
= wxTheApp
->OnRun();
718 // we want to initialize, but not run or exit immediately.
722 //else: app initialization failed, so we skipped OnRun()
724 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
727 // Forcibly delete the window.
728 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
729 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
731 topWindow
->Close(TRUE
);
732 wxTheApp
->DeletePendingObjects();
737 wxTheApp
->SetTopWindow(NULL
);
747 #if wxUSE_ON_FATAL_EXCEPTION
749 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
750 : EXCEPTION_CONTINUE_SEARCH
) {
753 // give the user a chance to do something special about this
754 wxTheApp
->OnFatalException();
757 ::ExitProcess(3); // the same exit code as abort()
761 #endif // wxUSE_ON_FATAL_EXCEPTION
764 // restore warning state
766 #pragma warning(default: 4715) // not all control paths return a value
771 //----------------------------------------------------------------------
772 // Entry point for wxWindows + the App in a DLL
773 //----------------------------------------------------------------------
775 int wxEntry(WXHINSTANCE hInstance
)
777 wxhInstance
= (HINSTANCE
) hInstance
;
780 // The app may have declared a global application object, but we recommend
781 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
782 // for delayed, dynamic app object construction.
785 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
786 "No initializer - use IMPLEMENT_APP macro." );
788 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
791 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
794 wxTheApp
->argv
= NULL
;
800 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
801 if ( topWindow
&& topWindow
->GetHWND())
803 topWindow
->Show(TRUE
);
810 //// Static member initialization
812 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
818 m_printMode
= wxPRINT_WINDOWS
;
824 // Delete command-line args
826 for (i
= 0; i
< argc
; i
++)
833 bool wxApp::Initialized()
840 #else // Assume initialized if DLL (no way of telling)
846 * Get and process a message, returning FALSE if WM_QUIT
847 * received (and also set the flag telling the app to exit the main loop)
850 bool wxApp::DoMessage()
852 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
862 // should never happen, but let's test for it nevertheless
863 wxLogLastError(wxT("GetMessage"));
868 wxASSERT_MSG( wxThread::IsMain(),
869 wxT("only the main thread can process Windows messages") );
871 static bool s_hadGuiLock
= TRUE
;
872 static wxMsgArray s_aSavedMessages
;
874 // if a secondary thread owns is doing GUI calls, save all messages for
875 // later processing - we can't process them right now because it will
876 // lead to recursive library calls (and we're not reentrant)
877 if ( !wxGuiOwnedByMainThread() )
879 s_hadGuiLock
= FALSE
;
881 // leave out WM_COMMAND messages: too dangerous, sometimes
882 // the message will be processed twice
883 if ( !wxIsWaitingForThread() ||
884 s_currentMsg
.message
!= WM_COMMAND
)
886 s_aSavedMessages
.Add(s_currentMsg
);
893 // have we just regained the GUI lock? if so, post all of the saved
896 // FIXME of course, it's not _exactly_ the same as processing the
897 // messages normally - expect some things to break...
902 size_t count
= s_aSavedMessages
.GetCount();
903 for ( size_t n
= 0; n
< count
; n
++ )
905 MSG
& msg
= s_aSavedMessages
[n
];
907 DoMessage((WXMSG
*)&msg
);
910 s_aSavedMessages
.Empty();
913 #endif // wxUSE_THREADS
915 // Process the message
916 DoMessage((WXMSG
*)&s_currentMsg
);
922 void wxApp::DoMessage(WXMSG
*pMsg
)
924 if ( !ProcessMessage(pMsg
) )
926 ::TranslateMessage((MSG
*)pMsg
);
927 ::DispatchMessage((MSG
*)pMsg
);
932 * Keep trying to process messages until WM_QUIT
935 * If there are messages to be processed, they will all be
936 * processed and OnIdle will not be called.
937 * When there are no more messages, OnIdle is called.
938 * If OnIdle requests more time,
939 * it will be repeatedly called so long as there are no pending messages.
940 * A 'feature' of this is that once OnIdle has decided that no more processing
941 * is required, then it won't get processing time until further messages
942 * are processed (it'll sit in DoMessage).
945 int wxApp::MainLoop()
949 while ( m_keepGoing
)
952 wxMutexGuiLeaveOrEnter();
953 #endif // wxUSE_THREADS
955 while ( !Pending() && ProcessIdle() )
958 // a message came or no more idle processing to do
962 return s_currentMsg
.wParam
;
965 // Returns TRUE if more time is needed.
966 bool wxApp::ProcessIdle()
969 event
.SetEventObject(this);
972 return event
.MoreRequested();
975 void wxApp::ExitMainLoop()
977 // this will set m_keepGoing to FALSE a bit later
978 ::PostQuitMessage(0);
981 bool wxApp::Pending()
983 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
986 void wxApp::Dispatch()
992 * Give all windows a chance to preprocess
993 * the message. Some may have accelerator tables, or have
997 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
999 MSG
*msg
= (MSG
*)wxmsg
;
1000 HWND hwnd
= msg
->hwnd
;
1001 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1003 // this may happen if the event occured in a standard modeless dialog (the
1004 // only example of which I know of is the find/replace dialog) - then call
1005 // IsDialogMessage() to make TAB navigation in it work
1008 // we need to find the dialog containing this control as
1009 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1010 // them) if we call it for the control itself
1011 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1013 hwnd
= ::GetParent(hwnd
);
1016 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1020 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1021 // popup the tooltip bubbles
1022 if ( (msg
->message
== WM_MOUSEMOVE
) )
1024 wxToolTip
*tt
= wndThis
->GetToolTip();
1027 tt
->RelayEvent(wxmsg
);
1030 #endif // wxUSE_TOOLTIPS
1032 // allow the window to prevent certain messages from being
1033 // translated/processed (this is currently used by wxTextCtrl to always
1034 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1035 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1040 // try translations first: the accelerators override everything
1043 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1045 if ( wnd
->MSWTranslateMessage(wxmsg
))
1048 // stop at first top level window, i.e. don't try to process the key
1049 // strokes originating in a dialog using the accelerators of the parent
1050 // frame - this doesn't make much sense
1051 if ( wnd
->IsTopLevel() )
1055 // now try the other hooks (kbd navigation is handled here): we start from
1056 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1058 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1060 if ( wnd
->MSWProcessMessage(wxmsg
) )
1064 // no special preprocessing for this message, dispatch it normally
1068 void wxApp::OnIdle(wxIdleEvent
& event
)
1070 static bool s_inOnIdle
= FALSE
;
1072 // Avoid recursion (via ProcessEvent default case)
1078 // If there are pending events, we must process them: pending events
1079 // are either events to the threads other than main or events posted
1080 // with wxPostEvent() functions
1081 // GRG: I have moved this here so that all pending events are processed
1082 // before starting to delete any objects. This behaves better (in
1083 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1084 // behaviour. Changed Feb/2000 before 2.1.14
1085 ProcessPendingEvents();
1087 // 'Garbage' collection of windows deleted with Close().
1088 DeletePendingObjects();
1091 // flush the logged messages if any
1092 wxLog::FlushActive();
1095 #if wxUSE_DC_CACHEING
1096 // automated DC cache management: clear the cached DCs and bitmap
1097 // if it's likely that the app has finished with them, that is, we
1098 // get an idle event and we're not dragging anything.
1099 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1101 #endif // wxUSE_DC_CACHEING
1103 // Send OnIdle events to all windows
1104 if ( SendIdleEvents() )
1106 // SendIdleEvents() returns TRUE if at least one window requested more
1108 event
.RequestMore(TRUE
);
1114 // Send idle event to all top-level windows
1115 bool wxApp::SendIdleEvents()
1117 bool needMore
= FALSE
;
1119 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1122 wxWindow
* win
= node
->GetData();
1123 if (SendIdleEvents(win
))
1125 node
= node
->GetNext();
1131 // Send idle event to window and all subwindows
1132 bool wxApp::SendIdleEvents(wxWindow
* win
)
1134 bool needMore
= FALSE
;
1137 event
.SetEventObject(win
);
1138 win
->GetEventHandler()->ProcessEvent(event
);
1140 if (event
.MoreRequested())
1143 wxNode
* node
= win
->GetChildren().First();
1146 wxWindow
* win
= (wxWindow
*) node
->Data();
1147 if (SendIdleEvents(win
))
1150 node
= node
->Next();
1155 void wxApp::DeletePendingObjects()
1157 wxNode
*node
= wxPendingDelete
.First();
1160 wxObject
*obj
= (wxObject
*)node
->Data();
1164 if (wxPendingDelete
.Member(obj
))
1167 // Deleting one object may have deleted other pending
1168 // objects, so start from beginning of list again.
1169 node
= wxPendingDelete
.First();
1173 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1176 GetTopWindow()->Close(TRUE
);
1179 // Default behaviour: close the application with prompts. The
1180 // user can veto the close, and therefore the end session.
1181 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1185 if (!GetTopWindow()->Close(!event
.CanVeto()))
1191 int wxApp::GetComCtl32Version()
1193 #ifdef __WXMICROWIN__
1197 static int s_verComCtl32
= -1;
1199 wxCRIT_SECT_DECLARE(csComCtl32
);
1200 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1202 if ( s_verComCtl32
== -1 )
1204 // initally assume no comctl32.dll at all
1208 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1210 // if so, then we can check for the version
1211 if ( hModuleComCtl32
)
1213 // try to use DllGetVersion() if available in _headers_
1214 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1215 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1216 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1217 if ( pfnDllGetVersion
)
1220 dvi
.cbSize
= sizeof(dvi
);
1222 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1225 wxLogApiError(_T("DllGetVersion"), hr
);
1229 // this is incompatible with _WIN32_IE values, but
1230 // compatible with the other values returned by
1231 // GetComCtl32Version()
1232 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1237 // DllGetVersion() unavailable either during compile or
1238 // run-time, try to guess the version otherwise
1239 if ( !s_verComCtl32
)
1241 // InitCommonControlsEx is unique to 4.70 and later
1242 FARPROC theProc
= ::GetProcAddress
1245 "InitCommonControlsEx"
1250 // not found, must be 4.00
1251 s_verComCtl32
= 400;
1255 // many symbols appeared in comctl32 4.71, could use
1256 // any of them except may be DllInstall
1257 theProc
= ::GetProcAddress
1264 // not found, must be 4.70
1265 s_verComCtl32
= 470;
1269 // found, must be 4.71
1270 s_verComCtl32
= 471;
1277 return s_verComCtl32
;
1283 wxLogError(_("Fatal error: exiting"));
1289 // Yield to incoming messages
1291 bool wxApp::Yield(bool onlyIfNeeded
)
1294 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
1302 if ( !onlyIfNeeded
)
1304 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1312 // we don't want to process WM_QUIT from here - it should be processed in
1313 // the main event loop in order to stop it
1315 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1316 msg
.message
!= WM_QUIT
)
1319 wxMutexGuiLeaveOrEnter();
1320 #endif // wxUSE_THREADS
1322 if ( !wxTheApp
->DoMessage() )
1326 // if there are pending events, we must process them.
1327 ProcessPendingEvents();
1329 // let the logs be flashed again
1337 bool wxHandleFatalExceptions(bool doit
)
1339 #if wxUSE_ON_FATAL_EXCEPTION
1340 // assume this can only be called from the main thread
1341 gs_handleExceptions
= doit
;
1345 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1352 //-----------------------------------------------------------------------------
1354 //-----------------------------------------------------------------------------
1358 // Send the top window a dummy message so idle handler processing will
1359 // start up again. Doing it this way ensures that the idle handler
1360 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1361 // the same for the main app thread only)
1362 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1365 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1367 // should never happen
1368 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1373 //-----------------------------------------------------------------------------
1375 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1376 // if in a separate file. So include it here to ensure it's linked.
1377 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))