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/module.h"
53 #include "wx/msw/private.h"
56 #include "wx/thread.h"
58 // define the array of MSG strutures
59 WX_DECLARE_OBJARRAY(MSG
, wxMsgArray
);
61 #include "wx/arrimpl.cpp"
63 WX_DEFINE_OBJARRAY(wxMsgArray
);
64 #endif // wxUSE_THREADS
66 #if wxUSE_WX_RESOURCES
67 #include "wx/resource.h"
70 // OLE is used for drag-and-drop, clipboard, OLE Automation...
71 #ifndef wxUSE_NORLANDER_HEADERS
72 #if defined(__GNUWIN32__) || defined(__SC__) || defined(__SALFORDC__)
76 #endif // broken compilers
86 #if (defined(__WIN95__) && !defined(__GNUWIN32__)) || defined(__TWIN32__) || defined(wxUSE_NORLANDER_HEADERS)
91 #include "wx/msw/msvcrt.h"
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
97 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
98 // defined before) and shows us what common control features are available
99 // during the compile time (it doesn't mean that they will be available during
100 // the run-time, use GetComCtl32Version() to test for them!). The possible
103 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
104 // 0x0300 4.70 IE 3.x
105 // 0x0400 4.71 IE 4.0
106 // 0x0401 4.72 IE 4.01 and Win98
107 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
110 // minimal set of features by default
111 #define _WIN32_IE 0x0200
114 // ---------------------------------------------------------------------------
116 // ---------------------------------------------------------------------------
118 extern wxChar
*wxBuffer
;
119 extern wxChar
*wxOsVersion
;
120 extern wxList
*wxWinHandleList
;
121 extern wxList WXDLLEXPORT wxPendingDelete
;
122 extern void wxSetKeyboardHook(bool doIt
);
123 extern wxCursor
*g_globalCursor
;
126 wxApp
*wxTheApp
= NULL
;
128 // FIXME why not const? and not static?
130 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
131 // with NR suffix - wxWindow::MSWCreate() supposes this
132 wxChar wxFrameClassName
[] = wxT("wxFrameClass");
133 wxChar wxFrameClassNameNoRedraw
[] = wxT("wxFrameClassNR");
134 wxChar wxMDIFrameClassName
[] = wxT("wxMDIFrameClass");
135 wxChar wxMDIFrameClassNameNoRedraw
[] = wxT("wxMDIFrameClassNR");
136 wxChar wxMDIChildFrameClassName
[] = wxT("wxMDIChildFrameClass");
137 wxChar wxMDIChildFrameClassNameNoRedraw
[] = wxT("wxMDIChildFrameClassNR");
138 wxChar wxPanelClassName
[] = wxT("wxPanelClass");
139 wxChar wxCanvasClassName
[] = wxT("wxCanvasClass");
141 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
142 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
143 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
145 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
146 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
147 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
149 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
151 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
154 // the handle to richedit DLL and the version of the DLL loaded
155 static HINSTANCE gs_hRichEdit
= (HINSTANCE
)NULL
;
156 static int gs_verRichEdit
= -1;
159 // ===========================================================================
161 // ===========================================================================
163 // ---------------------------------------------------------------------------
165 // ---------------------------------------------------------------------------
167 #if !USE_SHARED_LIBRARY
168 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
170 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
171 EVT_IDLE(wxApp::OnIdle
)
172 EVT_END_SESSION(wxApp::OnEndSession
)
173 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
178 bool wxApp::Initialize()
180 // Some people may wish to use this, but
181 // probably it shouldn't be here by default.
183 // wxRedirectIOToConsole();
186 wxBuffer
= new wxChar
[1500]; // FIXME
188 wxClassInfo::InitializeClasses();
191 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
195 wxPendingEventsLocker
= new wxCriticalSection
;
198 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
199 wxTheColourDatabase
->Initialize();
201 wxInitializeStockLists();
202 wxInitializeStockObjects();
204 #if wxUSE_WX_RESOURCES
205 wxInitializeResourceSystem();
208 wxBitmap::InitStandardHandlers();
210 #if defined(__WIN95__)
211 InitCommonControls();
218 // for OLE, enlarge message queue to be as large as possible
220 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
223 // we need to initialize OLE library
224 if ( FAILED(::OleInitialize(NULL
)) )
225 wxLogError(_("Cannot initialize OLE"));
229 if (!Ctl3dRegister(wxhInstance
))
230 wxLogError(wxT("Cannot register CTL3D"));
232 Ctl3dAutoSubclass(wxhInstance
);
235 g_globalCursor
= new wxCursor
;
237 // VZ: these icons are not in wx.rc anyhow (but should they?)!
239 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
240 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
241 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
243 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
244 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
245 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
248 RegisterWindowClasses();
250 // Create the brush for disabling bitmap buttons
253 lb
.lbStyle
= BS_PATTERN
;
254 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
257 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
258 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
260 //else: wxWindows resources are probably not linked in
266 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
268 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
269 // PLEASE DO NOT ALTER THIS.
270 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
271 extern char wxDummyChar
;
272 if (wxDummyChar
) wxDummyChar
++;
275 wxSetKeyboardHook(TRUE
);
277 wxModule::RegisterModules();
278 if (!wxModule::InitializeModules())
283 // ---------------------------------------------------------------------------
284 // RegisterWindowClasses
285 // ---------------------------------------------------------------------------
287 // TODO we should only register classes really used by the app. For this it
288 // would be enough to just delay the class registration until an attempt
289 // to create a window of this class is made.
290 bool wxApp::RegisterWindowClasses()
294 // for each class we register one with CS_(V|H)REDRAW style and one
295 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
296 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
297 static const long styleNoRedraw
= CS_DBLCLKS
;
299 // the fields which are common to all classes
300 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
301 wndclass
.cbClsExtra
= 0;
302 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
303 wndclass
.hInstance
= wxhInstance
;
304 wndclass
.hIcon
= (HICON
) NULL
;
305 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
306 wndclass
.lpszMenuName
= NULL
;
308 // Register the frame window class.
309 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
310 wndclass
.lpszClassName
= wxFrameClassName
;
311 wndclass
.style
= styleNormal
;
313 if ( !RegisterClass(&wndclass
) )
315 wxLogLastError("RegisterClass(frame)");
321 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
322 wndclass
.style
= styleNoRedraw
;
324 if ( !RegisterClass(&wndclass
) )
326 wxLogLastError("RegisterClass(no redraw frame)");
331 // Register the MDI frame window class.
332 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
333 wndclass
.lpszClassName
= wxMDIFrameClassName
;
334 wndclass
.style
= styleNormal
;
336 if ( !RegisterClass(&wndclass
) )
338 wxLogLastError("RegisterClass(MDI parent)");
343 // "no redraw" MDI frame
344 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
345 wndclass
.style
= styleNoRedraw
;
347 if ( !RegisterClass(&wndclass
) )
349 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
354 // Register the MDI child frame window class.
355 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
356 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
357 wndclass
.style
= styleNormal
;
359 if ( !RegisterClass(&wndclass
) )
361 wxLogLastError("RegisterClass(MDI child)");
366 // "no redraw" MDI child frame
367 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
368 wndclass
.style
= styleNoRedraw
;
370 if ( !RegisterClass(&wndclass
) )
372 wxLogLastError("RegisterClass(no redraw MDI child)");
377 // Register the panel window class.
378 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
379 wndclass
.lpszClassName
= wxPanelClassName
;
380 wndclass
.style
= styleNormal
;
382 if ( !RegisterClass(&wndclass
) )
384 wxLogLastError("RegisterClass(panel)");
389 // Register the canvas and textsubwindow class name
390 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
391 wndclass
.lpszClassName
= wxCanvasClassName
;
393 if ( !RegisterClass(&wndclass
) )
395 wxLogLastError("RegisterClass(canvas)");
403 // ---------------------------------------------------------------------------
404 // Convert Windows to argc, argv style
405 // ---------------------------------------------------------------------------
407 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
411 wxString
cmdLine(lpCmdLine
);
414 // Get application name
415 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
416 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
421 wxStrcpy(name
, wxFileNameFromPath(name
));
422 wxStripExtension(name
);
423 wxTheApp
->SetAppName(name
);
426 // Treat strings enclosed in double-quotes as single arguments
428 int len
= cmdLine
.Length();
432 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
437 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
441 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
444 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
450 i
++; // Skip past 2nd quote
452 else // Unquoted argument
455 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
458 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
466 wxTheApp
->argv
= new wxChar
*[count
+ 1];
467 for (i
= 0; i
< count
; i
++)
469 wxString
arg(args
[i
]);
470 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
472 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
473 wxTheApp
->argc
= count
;
476 //// Cleans up any wxWindows internal structures left lying around
478 void wxApp::CleanUp()
483 // flush the logged messages if any and install a 'safer' log target: the
484 // default one (wxLogGui) can't be used after the resources are freed just
485 // below and the user suppliedo ne might be even more unsafe (using any
486 // wxWindows GUI function is unsafe starting from now)
487 wxLog::DontCreateOnDemand();
489 // this will flush the old messages if any
490 delete wxLog::SetActiveTarget(new wxLogStderr
);
493 // One last chance for pending objects to be cleaned up
494 wxTheApp
->DeletePendingObjects();
496 wxModule::CleanUpModules();
498 #if wxUSE_WX_RESOURCES
499 wxCleanUpResourceSystem();
501 // wxDefaultResourceTable->ClearTable();
504 // Indicate that the cursor can be freed, so that cursor won't be deleted
505 // by deleting the bitmap list before g_globalCursor goes out of scope
506 // (double deletion of the cursor).
507 wxSetCursor(wxNullCursor
);
508 delete g_globalCursor
;
509 g_globalCursor
= NULL
;
511 wxDeleteStockObjects();
513 // Destroy all GDI lists, etc.
514 wxDeleteStockLists();
516 delete wxTheColourDatabase
;
517 wxTheColourDatabase
= NULL
;
519 wxBitmap::CleanUpHandlers();
524 //// WINDOWS-SPECIFIC CLEANUP
526 wxSetKeyboardHook(FALSE
);
529 if (gs_hRichEdit
!= (HINSTANCE
) NULL
)
530 FreeLibrary(gs_hRichEdit
);
537 if (wxSTD_FRAME_ICON
)
538 DestroyIcon(wxSTD_FRAME_ICON
);
539 if (wxSTD_MDICHILDFRAME_ICON
)
540 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
541 if (wxSTD_MDIPARENTFRAME_ICON
)
542 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
544 if (wxDEFAULT_FRAME_ICON
)
545 DestroyIcon(wxDEFAULT_FRAME_ICON
);
546 if (wxDEFAULT_MDICHILDFRAME_ICON
)
547 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
548 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
549 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
551 if ( wxDisableButtonBrush
)
552 ::DeleteObject( wxDisableButtonBrush
);
559 Ctl3dUnregister(wxhInstance
);
563 delete wxWinHandleList
;
565 // GL: I'm annoyed ... I don't know where to put this and I don't want to
566 // create a module for that as it's part of the core.
567 delete wxPendingEvents
;
569 delete wxPendingEventsLocker
;
570 // If we don't do the following, we get an apparent memory leak.
571 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
574 wxClassInfo::CleanUpClasses();
579 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
580 // At this point we want to check if there are any memory
581 // blocks that aren't part of the wxDebugContext itself,
582 // as a special case. Then when dumping we need to ignore
583 // wxDebugContext, too.
584 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
586 wxLogDebug(wxT("There were memory leaks."));
587 wxDebugContext::Dump();
588 wxDebugContext::PrintStatistics();
590 // wxDebugContext::SetStream(NULL, NULL);
594 // do it as the very last thing because everything else can log messages
595 delete wxLog::SetActiveTarget(NULL
);
599 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
601 // temporarily disable this warning which would be generated in release builds
604 #pragma warning(disable: 4715) // not all control paths return a value
607 //// Main wxWindows entry point
608 int wxEntry(WXHINSTANCE hInstance
,
609 WXHINSTANCE
WXUNUSED(hPrevInstance
),
614 // do check for memory leaks on program exit
615 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
616 // deallocated memory which may be used to simulate low-memory condition)
617 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
619 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
620 // This seems to be necessary since there are 'rogue'
621 // objects present at this point (perhaps global objects?)
622 // Setting a checkpoint will ignore them as far as the
623 // memory checking facility is concerned.
624 // Of course you may argue that memory allocated in globals should be
625 // checked, but this is a reasonable compromise.
626 wxDebugContext::SetCheckpoint();
629 // take everything into a try-except block in release build
630 // FIXME other compilers must support Win32 SEH (structured exception
631 // handling) too, just find the appropriate keyword in their docs!
632 // Please note that it's _not_ the same as C++ exceptions!
633 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
634 #define CATCH_PROGRAM_EXCEPTIONS
638 #undef CATCH_PROGRAM_EXCEPTIONS
640 wxhInstance
= (HINSTANCE
) hInstance
;
642 if (!wxApp::Initialize())
645 // create the application object or ensure that one already exists
648 // The app may have declared a global application object, but we recommend
649 // the IMPLEMENT_APP macro is used instead, which sets an initializer
650 // function for delayed, dynamic app object construction.
651 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
652 wxT("No initializer - use IMPLEMENT_APP macro.") );
654 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
657 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
659 // save the WinMain() parameters
660 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
661 wxTheApp
->m_nCmdShow
= nCmdShow
;
663 // GUI-specific initialisation. In fact on Windows we don't have any,
664 // but this call is provided for compatibility across platforms.
665 wxTheApp
->OnInitGui();
667 // We really don't want timestamps by default, because it means
668 // we can't simply double-click on the error message and get to that
669 // line in the source. So VC++ at least, let's have a sensible default.
671 wxLog::SetTimestamp(NULL
);
676 if ( wxTheApp
->OnInit() )
680 retValue
= wxTheApp
->OnRun();
683 // We want to initialize, but not run or exit immediately.
686 //else: app initialization failed, so we skipped OnRun()
688 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
691 // Forcibly delete the window.
692 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
693 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
695 topWindow
->Close(TRUE
);
696 wxTheApp
->DeletePendingObjects();
701 wxTheApp
->SetTopWindow(NULL
);
711 #ifdef CATCH_PROGRAM_EXCEPTIONS
713 __except ( EXCEPTION_EXECUTE_HANDLER
) {
716 wxTheApp->OnFatalException();
719 // using wxLog would be unsafe here
721 _("Unrecoverable program error detected: "
722 " the application will terminate."),
724 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
726 ::ExitProcess(3); // the same exit code as abort()
730 #endif // CATCH_PROGRAM_EXCEPTIONS
733 // restore warning state
735 #pragma warning(default: 4715) // not all control paths return a value
740 //// Entry point for DLLs
742 int wxEntry(WXHINSTANCE hInstance
)
744 wxhInstance
= (HINSTANCE
) hInstance
;
747 // The app may have declared a global application object, but we recommend
748 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
749 // for delayed, dynamic app object construction.
752 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
753 "No initializer - use IMPLEMENT_APP macro." );
755 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
758 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
761 wxTheApp
->argv
= NULL
;
763 wxTheApp
->OnInitGui();
767 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
768 if ( topWindow
&& topWindow
->GetHWND())
770 topWindow
->Show(TRUE
);
777 //// Static member initialization
779 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
785 m_wantDebugOutput
= TRUE
;
789 m_printMode
= wxPRINT_WINDOWS
;
790 m_exitOnFrameDelete
= TRUE
;
796 // Delete command-line args
798 for (i
= 0; i
< argc
; i
++)
805 bool wxApp::Initialized()
813 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
819 * Get and process a message, returning FALSE if WM_QUIT
820 * received (and also set the flag telling the app to exit the main loop)
823 bool wxApp::DoMessage()
825 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
835 // should never happen, but let's test for it nevertheless
836 wxLogLastError("GetMessage");
841 wxASSERT_MSG( wxThread::IsMain(),
842 wxT("only the main thread can process Windows messages") );
844 static bool s_hadGuiLock
= TRUE
;
845 static wxMsgArray s_aSavedMessages
;
847 // if a secondary thread owns is doing GUI calls, save all messages for
848 // later processing - we can't process them right now because it will
849 // lead to recursive library calls (and we're not reentrant)
850 if ( !wxGuiOwnedByMainThread() )
852 s_hadGuiLock
= FALSE
;
854 // leave out WM_COMMAND messages: too dangerous, sometimes
855 // the message will be processed twice
856 if ( !wxIsWaitingForThread() ||
857 s_currentMsg
.message
!= WM_COMMAND
)
859 s_aSavedMessages
.Add(s_currentMsg
);
866 // have we just regained the GUI lock? if so, post all of the saved
869 // FIXME of course, it's not _exactly_ the same as processing the
870 // messages normally - expect some things to break...
875 size_t count
= s_aSavedMessages
.Count();
876 for ( size_t n
= 0; n
< count
; n
++ )
878 MSG
& msg
= s_aSavedMessages
[n
];
880 if ( !ProcessMessage((WXMSG
*)&msg
) )
882 ::TranslateMessage(&msg
);
883 ::DispatchMessage(&msg
);
887 s_aSavedMessages
.Empty();
890 #endif // wxUSE_THREADS
892 // Process the message
893 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
895 ::TranslateMessage(&s_currentMsg
);
896 ::DispatchMessage(&s_currentMsg
);
904 * Keep trying to process messages until WM_QUIT
907 * If there are messages to be processed, they will all be
908 * processed and OnIdle will not be called.
909 * When there are no more messages, OnIdle is called.
910 * If OnIdle requests more time,
911 * it will be repeatedly called so long as there are no pending messages.
912 * A 'feature' of this is that once OnIdle has decided that no more processing
913 * is required, then it won't get processing time until further messages
914 * are processed (it'll sit in DoMessage).
917 int wxApp::MainLoop()
921 while ( m_keepGoing
)
924 wxMutexGuiLeaveOrEnter();
925 #endif // wxUSE_THREADS
927 while ( !::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) &&
936 return s_currentMsg
.wParam
;
939 // Returns TRUE if more time is needed.
940 bool wxApp::ProcessIdle()
943 event
.SetEventObject(this);
946 return event
.MoreRequested();
949 void wxApp::ExitMainLoop()
954 bool wxApp::Pending()
956 return (::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0);
959 void wxApp::Dispatch()
965 * Give all windows a chance to preprocess
966 * the message. Some may have accelerator tables, or have
970 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
972 MSG
*msg
= (MSG
*)wxmsg
;
973 HWND hWnd
= msg
->hwnd
;
974 wxWindow
*wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
), *wnd
;
976 // for some composite controls (like a combobox), wndThis might be NULL
977 // because the subcontrol is not a wxWindow, but only the control itself
978 // is - try to catch this case
979 while ( hWnd
&& !wndThis
)
981 hWnd
= ::GetParent(hWnd
);
982 wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
);
985 // Try translations first; find the youngest window with
986 // a translation table.
987 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
989 if ( wnd
->MSWTranslateMessage(wxmsg
) )
993 // Anyone for a non-translation message? Try youngest descendants first.
994 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
996 if ( wnd
->MSWProcessMessage(wxmsg
) )
1003 void wxApp::OnIdle(wxIdleEvent
& event
)
1005 static bool s_inOnIdle
= FALSE
;
1007 // Avoid recursion (via ProcessEvent default case)
1013 // 'Garbage' collection of windows deleted with Close().
1014 DeletePendingObjects();
1017 // flush the logged messages if any
1018 wxLog
*pLog
= wxLog::GetActiveTarget();
1019 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
1023 // Send OnIdle events to all windows
1024 if ( SendIdleEvents() )
1026 // SendIdleEvents() returns TRUE if at least one window requested more
1028 event
.RequestMore(TRUE
);
1031 // If they are pending events, we must process them: pending events are
1032 // either events to the threads other than main or events posted with
1033 // wxPostEvent() functions
1034 ProcessPendingEvents();
1039 // Send idle event to all top-level windows
1040 bool wxApp::SendIdleEvents()
1042 bool needMore
= FALSE
;
1044 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1047 wxWindow
* win
= node
->GetData();
1048 if (SendIdleEvents(win
))
1050 node
= node
->GetNext();
1056 // Send idle event to window and all subwindows
1057 bool wxApp::SendIdleEvents(wxWindow
* win
)
1059 bool needMore
= FALSE
;
1062 event
.SetEventObject(win
);
1063 win
->GetEventHandler()->ProcessEvent(event
);
1065 if (event
.MoreRequested())
1068 wxNode
* node
= win
->GetChildren().First();
1071 wxWindow
* win
= (wxWindow
*) node
->Data();
1072 if (SendIdleEvents(win
))
1075 node
= node
->Next();
1080 void wxApp::DeletePendingObjects()
1082 wxNode
*node
= wxPendingDelete
.First();
1085 wxObject
*obj
= (wxObject
*)node
->Data();
1089 if (wxPendingDelete
.Member(obj
))
1092 // Deleting one object may have deleted other pending
1093 // objects, so start from beginning of list again.
1094 node
= wxPendingDelete
.First();
1098 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1101 GetTopWindow()->Close(TRUE
);
1104 // Default behaviour: close the application with prompts. The
1105 // user can veto the close, and therefore the end session.
1106 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1110 if (!GetTopWindow()->Close(!event
.CanVeto()))
1118 bool wxApp::InitRichEdit(int version
)
1120 wxCHECK_MSG( version
>= 1 && version
<= 3, FALSE
,
1121 _T("incorrect richedit control version requested") );
1123 if ( version
<= gs_verRichEdit
)
1125 // we've already got this or better
1131 ::FreeLibrary(gs_hRichEdit
);
1134 // always try load riched20.dll first - like this we won't have to reload
1135 // it later if we're first asked for RE 1 and then for RE 2 or 3
1136 wxString dllname
= _T("riched20.dll");
1137 gs_hRichEdit
= ::LoadLibrary(dllname
);
1138 if ( !gs_hRichEdit
&& (version
== 1) )
1140 // fall back to RE 1
1141 dllname
= _T("riched32.dll");
1142 gs_hRichEdit
= ::LoadLibrary(dllname
);
1145 if ( !gs_hRichEdit
)
1147 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname
.c_str());
1149 gs_verRichEdit
= -1;
1154 gs_verRichEdit
= version
;
1159 #endif // wxUSE_RICHEDIT
1162 int wxApp::GetComCtl32Version()
1165 static int s_verComCtl32
= -1;
1167 wxCRIT_SECT_DECLARE(csComCtl32
);
1168 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1170 if ( s_verComCtl32
== -1 )
1172 // initally assume no comctl32.dll at all
1176 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1178 // if so, then we can check for the version
1179 if ( hModuleComCtl32
)
1181 // try to use DllGetVersion() if available in _headers_
1182 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1183 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1184 ::GetProcAddress(hModuleComCtl32
, _T("DllGetVersion"));
1185 if ( pfnDllGetVersion
)
1188 dvi
.cbSize
= sizeof(dvi
);
1190 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1193 wxLogApiError(_T("DllGetVersion"), hr
);
1197 // this is incompatible with _WIN32_IE values, but
1198 // compatible with the other values returned by
1199 // GetComCtl32Version()
1200 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1205 // DllGetVersion() unavailable either during compile or
1206 // run-time, try to guess the version otherwise
1207 if ( !s_verComCtl32
)
1209 // InitCommonControlsEx is unique to 4.70 and later
1210 FARPROC theProc
= ::GetProcAddress
1213 _T("InitCommonControlsEx")
1218 // not found, must be 4.00
1219 s_verComCtl32
= 400;
1223 // many symbols appeared in comctl32 4.71, could use
1224 // any of them except may be DllInstall
1225 theProc
= ::GetProcAddress
1228 _T("InitializeFlatSB")
1232 // not found, must be 4.70
1233 s_verComCtl32
= 470;
1237 // found, must be 4.71
1238 s_verComCtl32
= 471;
1245 return s_verComCtl32
;
1250 wxLogError(_("Fatal error: exiting"));
1255 // Yield to incoming messages
1258 // we don't want to process WM_QUIT from here - it should be processed in
1259 // the main event loop in order to stop it
1262 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1263 msg
.message
!= WM_QUIT
)
1265 if ( !wxTheApp
->DoMessage() )
1269 // If they are pending events, we must process them.
1270 wxTheApp
->ProcessPendingEvents();
1275 //-----------------------------------------------------------------------------
1277 //-----------------------------------------------------------------------------
1281 // Send the top window a dummy message so idle handler processing will
1282 // start up again. Doing it this way ensures that the idle handler
1283 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1284 // the same for the main app thread only)
1285 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1288 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1290 // should never happen
1291 wxLogLastError("PostMessage(WM_NULL)");
1296 //-----------------------------------------------------------------------------
1299 wxApp::GetStdIcon(int which
) const
1303 case wxICON_INFORMATION
:
1304 return wxIcon("wxICON_INFO");
1306 case wxICON_QUESTION
:
1307 return wxIcon("wxICON_QUESTION");
1309 case wxICON_EXCLAMATION
:
1310 return wxIcon("wxICON_WARNING");
1313 wxFAIL_MSG(wxT("requested non existent standard icon"));
1314 // still fall through
1317 return wxIcon("wxICON_ERROR");
1321 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1322 // if in a separate file. So include it here to ensure it's linked.
1323 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))