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)
90 #include "wx/msw/msvcrt.h"
92 // ----------------------------------------------------------------------------
93 // conditional compilation
94 // ----------------------------------------------------------------------------
96 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
97 // defined before) and shows us what common control features are available
98 // during the compile time (it doesn't mean that they will be available during
99 // the run-time, use GetComCtl32Version() to test for them!). The possible
102 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
103 // 0x0300 4.70 IE 3.x
104 // 0x0400 4.71 IE 4.0
105 // 0x0401 4.72 IE 4.01 and Win98
106 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
109 // minimal set of features by default
110 #define _WIN32_IE 0x0200
113 #if _WIN32_IE >= 0x0300
117 // ---------------------------------------------------------------------------
119 // ---------------------------------------------------------------------------
121 extern wxChar
*wxBuffer
;
122 extern wxChar
*wxOsVersion
;
123 extern wxList
*wxWinHandleList
;
124 extern wxList WXDLLEXPORT wxPendingDelete
;
125 extern void wxSetKeyboardHook(bool doIt
);
126 extern wxCursor
*g_globalCursor
;
129 wxApp
*wxTheApp
= NULL
;
131 // FIXME why not const? and not static?
133 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
134 // with NR suffix - wxWindow::MSWCreate() supposes this
135 wxChar wxFrameClassName
[] = wxT("wxFrameClass");
136 wxChar wxFrameClassNameNoRedraw
[] = wxT("wxFrameClassNR");
137 wxChar wxMDIFrameClassName
[] = wxT("wxMDIFrameClass");
138 wxChar wxMDIFrameClassNameNoRedraw
[] = wxT("wxMDIFrameClassNR");
139 wxChar wxMDIChildFrameClassName
[] = wxT("wxMDIChildFrameClass");
140 wxChar wxMDIChildFrameClassNameNoRedraw
[] = wxT("wxMDIChildFrameClassNR");
141 wxChar wxPanelClassName
[] = wxT("wxPanelClass");
142 wxChar wxCanvasClassName
[] = wxT("wxCanvasClass");
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
);
157 // the handle to richedit DLL and the version of the DLL loaded
158 static HINSTANCE gs_hRichEdit
= (HINSTANCE
)NULL
;
159 static int gs_verRichEdit
= -1;
162 // ===========================================================================
164 // ===========================================================================
166 // ---------------------------------------------------------------------------
168 // ---------------------------------------------------------------------------
170 #if !USE_SHARED_LIBRARY
171 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
173 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
174 EVT_IDLE(wxApp::OnIdle
)
175 EVT_END_SESSION(wxApp::OnEndSession
)
176 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
181 bool wxApp::Initialize()
183 // Some people may wish to use this, but
184 // probably it shouldn't be here by default.
186 // wxRedirectIOToConsole();
189 wxBuffer
= new wxChar
[1500]; // FIXME
191 wxClassInfo::InitializeClasses();
194 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
198 wxPendingEventsLocker
= new wxCriticalSection
;
201 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
202 wxTheColourDatabase
->Initialize();
204 wxInitializeStockLists();
205 wxInitializeStockObjects();
207 #if wxUSE_WX_RESOURCES
208 wxInitializeResourceSystem();
211 wxBitmap::InitStandardHandlers();
213 #if defined(__WIN95__)
214 InitCommonControls();
221 // for OLE, enlarge message queue to be as large as possible
223 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
226 // we need to initialize OLE library
227 if ( FAILED(::OleInitialize(NULL
)) )
228 wxLogError(_("Cannot initialize OLE"));
232 if (!Ctl3dRegister(wxhInstance
))
233 wxLogError(wxT("Cannot register CTL3D"));
235 Ctl3dAutoSubclass(wxhInstance
);
238 g_globalCursor
= new wxCursor
;
240 // VZ: these icons are not in wx.rc anyhow (but should they?)!
242 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
243 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
244 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
246 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
247 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
248 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
251 RegisterWindowClasses();
253 // Create the brush for disabling bitmap buttons
256 lb
.lbStyle
= BS_PATTERN
;
257 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
260 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
261 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
263 //else: wxWindows resources are probably not linked in
269 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
271 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
272 // PLEASE DO NOT ALTER THIS.
273 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
274 extern char wxDummyChar
;
275 if (wxDummyChar
) wxDummyChar
++;
278 wxSetKeyboardHook(TRUE
);
280 wxModule::RegisterModules();
281 if (!wxModule::InitializeModules())
286 // ---------------------------------------------------------------------------
287 // RegisterWindowClasses
288 // ---------------------------------------------------------------------------
290 // TODO we should only register classes really used by the app. For this it
291 // would be enough to just delay the class registration until an attempt
292 // to create a window of this class is made.
293 bool wxApp::RegisterWindowClasses()
297 // for each class we register one with CS_(V|H)REDRAW style and one
298 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
299 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
300 static const long styleNoRedraw
= CS_DBLCLKS
;
302 // the fields which are common to all classes
303 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
304 wndclass
.cbClsExtra
= 0;
305 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
306 wndclass
.hInstance
= wxhInstance
;
307 wndclass
.hIcon
= (HICON
) NULL
;
308 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
309 wndclass
.lpszMenuName
= NULL
;
311 // Register the frame window class.
312 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
313 wndclass
.lpszClassName
= wxFrameClassName
;
314 wndclass
.style
= styleNormal
;
316 if ( !RegisterClass(&wndclass
) )
318 wxLogLastError("RegisterClass(frame)");
324 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
325 wndclass
.style
= styleNoRedraw
;
327 if ( !RegisterClass(&wndclass
) )
329 wxLogLastError("RegisterClass(no redraw frame)");
334 // Register the MDI frame window class.
335 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
336 wndclass
.lpszClassName
= wxMDIFrameClassName
;
337 wndclass
.style
= styleNormal
;
339 if ( !RegisterClass(&wndclass
) )
341 wxLogLastError("RegisterClass(MDI parent)");
346 // "no redraw" MDI frame
347 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
348 wndclass
.style
= styleNoRedraw
;
350 if ( !RegisterClass(&wndclass
) )
352 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
357 // Register the MDI child frame window class.
358 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
359 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
360 wndclass
.style
= styleNormal
;
362 if ( !RegisterClass(&wndclass
) )
364 wxLogLastError("RegisterClass(MDI child)");
369 // "no redraw" MDI child frame
370 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
371 wndclass
.style
= styleNoRedraw
;
373 if ( !RegisterClass(&wndclass
) )
375 wxLogLastError("RegisterClass(no redraw MDI child)");
380 // Register the panel window class.
381 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
382 wndclass
.lpszClassName
= wxPanelClassName
;
383 wndclass
.style
= styleNormal
;
385 if ( !RegisterClass(&wndclass
) )
387 wxLogLastError("RegisterClass(panel)");
392 // Register the canvas and textsubwindow class name
393 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
394 wndclass
.lpszClassName
= wxCanvasClassName
;
396 if ( !RegisterClass(&wndclass
) )
398 wxLogLastError("RegisterClass(canvas)");
406 // ---------------------------------------------------------------------------
407 // Convert Windows to argc, argv style
408 // ---------------------------------------------------------------------------
410 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
414 wxString
cmdLine(lpCmdLine
);
417 // Get application name
418 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
419 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
424 wxStrcpy(name
, wxFileNameFromPath(name
));
425 wxStripExtension(name
);
426 wxTheApp
->SetAppName(name
);
429 // Treat strings enclosed in double-quotes as single arguments
431 int len
= cmdLine
.Length();
435 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
440 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
444 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
447 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
453 i
++; // Skip past 2nd quote
455 else // Unquoted argument
458 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
461 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
469 wxTheApp
->argv
= new wxChar
*[count
+ 1];
470 for (i
= 0; i
< count
; i
++)
472 wxString
arg(args
[i
]);
473 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
475 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
476 wxTheApp
->argc
= count
;
479 //// Cleans up any wxWindows internal structures left lying around
481 void wxApp::CleanUp()
486 // flush the logged messages if any and install a 'safer' log target: the
487 // default one (wxLogGui) can't be used after the resources are freed just
488 // below and the user suppliedo ne might be even more unsafe (using any
489 // wxWindows GUI function is unsafe starting from now)
490 wxLog::DontCreateOnDemand();
492 // this will flush the old messages if any
493 delete wxLog::SetActiveTarget(new wxLogStderr
);
496 // One last chance for pending objects to be cleaned up
497 wxTheApp
->DeletePendingObjects();
499 wxModule::CleanUpModules();
501 #if wxUSE_WX_RESOURCES
502 wxCleanUpResourceSystem();
504 // wxDefaultResourceTable->ClearTable();
507 // Indicate that the cursor can be freed, so that cursor won't be deleted
508 // by deleting the bitmap list before g_globalCursor goes out of scope
509 // (double deletion of the cursor).
510 wxSetCursor(wxNullCursor
);
511 delete g_globalCursor
;
512 g_globalCursor
= NULL
;
514 wxDeleteStockObjects();
516 // Destroy all GDI lists, etc.
517 wxDeleteStockLists();
519 delete wxTheColourDatabase
;
520 wxTheColourDatabase
= NULL
;
522 wxBitmap::CleanUpHandlers();
527 //// WINDOWS-SPECIFIC CLEANUP
529 wxSetKeyboardHook(FALSE
);
532 if (gs_hRichEdit
!= (HINSTANCE
) NULL
)
533 FreeLibrary(gs_hRichEdit
);
540 if (wxSTD_FRAME_ICON
)
541 DestroyIcon(wxSTD_FRAME_ICON
);
542 if (wxSTD_MDICHILDFRAME_ICON
)
543 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
544 if (wxSTD_MDIPARENTFRAME_ICON
)
545 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
547 if (wxDEFAULT_FRAME_ICON
)
548 DestroyIcon(wxDEFAULT_FRAME_ICON
);
549 if (wxDEFAULT_MDICHILDFRAME_ICON
)
550 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
551 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
552 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
554 if ( wxDisableButtonBrush
)
555 ::DeleteObject( wxDisableButtonBrush
);
562 Ctl3dUnregister(wxhInstance
);
566 delete wxWinHandleList
;
568 // GL: I'm annoyed ... I don't know where to put this and I don't want to
569 // create a module for that as it's part of the core.
570 delete wxPendingEvents
;
572 delete wxPendingEventsLocker
;
573 // If we don't do the following, we get an apparent memory leak.
574 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
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 wxLogDebug(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 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
604 // temporarily disable this warning which would be generated in release builds
607 #pragma warning(disable: 4715) // not all control paths return a value
610 //// Main wxWindows entry point
611 int wxEntry(WXHINSTANCE hInstance
,
612 WXHINSTANCE
WXUNUSED(hPrevInstance
),
617 // do check for memory leaks on program exit
618 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
619 // deallocated memory which may be used to simulate low-memory condition)
620 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
622 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
623 // This seems to be necessary since there are 'rogue'
624 // objects present at this point (perhaps global objects?)
625 // Setting a checkpoint will ignore them as far as the
626 // memory checking facility is concerned.
627 // Of course you may argue that memory allocated in globals should be
628 // checked, but this is a reasonable compromise.
629 wxDebugContext::SetCheckpoint();
632 // take everything into a try-except block in release build
633 // FIXME other compilers must support Win32 SEH (structured exception
634 // handling) too, just find the appropriate keyword in their docs!
635 // Please note that it's _not_ the same as C++ exceptions!
636 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
637 #define CATCH_PROGRAM_EXCEPTIONS
641 #undef CATCH_PROGRAM_EXCEPTIONS
643 wxhInstance
= (HINSTANCE
) hInstance
;
645 if (!wxApp::Initialize())
648 // create the application object or ensure that one already exists
651 // The app may have declared a global application object, but we recommend
652 // the IMPLEMENT_APP macro is used instead, which sets an initializer
653 // function for delayed, dynamic app object construction.
654 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
655 wxT("No initializer - use IMPLEMENT_APP macro.") );
657 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
660 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
662 // save the WinMain() parameters
663 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
664 wxTheApp
->m_nCmdShow
= nCmdShow
;
666 // GUI-specific initialisation. In fact on Windows we don't have any,
667 // but this call is provided for compatibility across platforms.
668 wxTheApp
->OnInitGui();
670 // We really don't want timestamps by default, because it means
671 // we can't simply double-click on the error message and get to that
672 // line in the source. So VC++ at least, let's have a sensible default.
674 wxLog::SetTimestamp(NULL
);
679 if ( wxTheApp
->OnInit() )
683 retValue
= wxTheApp
->OnRun();
686 // We want to initialize, but not run or exit immediately.
689 //else: app initialization failed, so we skipped OnRun()
691 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
694 // Forcibly delete the window.
695 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
696 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
698 topWindow
->Close(TRUE
);
699 wxTheApp
->DeletePendingObjects();
704 wxTheApp
->SetTopWindow(NULL
);
714 #ifdef CATCH_PROGRAM_EXCEPTIONS
716 __except ( EXCEPTION_EXECUTE_HANDLER
) {
719 wxTheApp->OnFatalException();
722 // using wxLog would be unsafe here
724 _("Unrecoverable program error detected: "
725 " the application will terminate."),
727 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
729 ::ExitProcess(3); // the same exit code as abort()
733 #endif // CATCH_PROGRAM_EXCEPTIONS
736 // restore warning state
738 #pragma warning(default: 4715) // not all control paths return a value
743 //// Entry point for DLLs
745 int wxEntry(WXHINSTANCE hInstance
)
747 wxhInstance
= (HINSTANCE
) hInstance
;
750 // The app may have declared a global application object, but we recommend
751 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
752 // for delayed, dynamic app object construction.
755 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
756 "No initializer - use IMPLEMENT_APP macro." );
758 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
761 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
764 wxTheApp
->argv
= NULL
;
766 wxTheApp
->OnInitGui();
770 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
771 if ( topWindow
&& topWindow
->GetHWND())
773 topWindow
->Show(TRUE
);
780 //// Static member initialization
782 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
788 m_wantDebugOutput
= TRUE
;
792 m_printMode
= wxPRINT_WINDOWS
;
793 m_exitOnFrameDelete
= TRUE
;
799 // Delete command-line args
801 for (i
= 0; i
< argc
; i
++)
808 bool wxApp::Initialized()
816 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
822 * Get and process a message, returning FALSE if WM_QUIT
823 * received (and also set the flag telling the app to exit the main loop)
826 bool wxApp::DoMessage()
828 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
838 // should never happen, but let's test for it nevertheless
839 wxLogLastError("GetMessage");
844 wxASSERT_MSG( wxThread::IsMain(),
845 wxT("only the main thread can process Windows messages") );
847 static bool s_hadGuiLock
= TRUE
;
848 static wxMsgArray s_aSavedMessages
;
850 // if a secondary thread owns is doing GUI calls, save all messages for
851 // later processing - we can't process them right now because it will
852 // lead to recursive library calls (and we're not reentrant)
853 if ( !wxGuiOwnedByMainThread() )
855 s_hadGuiLock
= FALSE
;
857 // leave out WM_COMMAND messages: too dangerous, sometimes
858 // the message will be processed twice
859 if ( !wxIsWaitingForThread() ||
860 s_currentMsg
.message
!= WM_COMMAND
)
862 s_aSavedMessages
.Add(s_currentMsg
);
869 // have we just regained the GUI lock? if so, post all of the saved
872 // FIXME of course, it's not _exactly_ the same as processing the
873 // messages normally - expect some things to break...
878 size_t count
= s_aSavedMessages
.Count();
879 for ( size_t n
= 0; n
< count
; n
++ )
881 MSG
& msg
= s_aSavedMessages
[n
];
883 if ( !ProcessMessage((WXMSG
*)&msg
) )
885 ::TranslateMessage(&msg
);
886 ::DispatchMessage(&msg
);
890 s_aSavedMessages
.Empty();
893 #endif // wxUSE_THREADS
895 // Process the message
896 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
898 ::TranslateMessage(&s_currentMsg
);
899 ::DispatchMessage(&s_currentMsg
);
907 * Keep trying to process messages until WM_QUIT
910 * If there are messages to be processed, they will all be
911 * processed and OnIdle will not be called.
912 * When there are no more messages, OnIdle is called.
913 * If OnIdle requests more time,
914 * it will be repeatedly called so long as there are no pending messages.
915 * A 'feature' of this is that once OnIdle has decided that no more processing
916 * is required, then it won't get processing time until further messages
917 * are processed (it'll sit in DoMessage).
920 int wxApp::MainLoop()
924 while ( m_keepGoing
)
927 wxMutexGuiLeaveOrEnter();
928 #endif // wxUSE_THREADS
930 while ( !::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) &&
939 return s_currentMsg
.wParam
;
942 // Returns TRUE if more time is needed.
943 bool wxApp::ProcessIdle()
946 event
.SetEventObject(this);
949 return event
.MoreRequested();
952 void wxApp::ExitMainLoop()
957 bool wxApp::Pending()
959 return (::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0);
962 void wxApp::Dispatch()
968 * Give all windows a chance to preprocess
969 * the message. Some may have accelerator tables, or have
973 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
975 MSG
*msg
= (MSG
*)wxmsg
;
976 HWND hWnd
= msg
->hwnd
;
977 wxWindow
*wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
), *wnd
;
979 // for some composite controls (like a combobox), wndThis might be NULL
980 // because the subcontrol is not a wxWindow, but only the control itself
981 // is - try to catch this case
982 while ( hWnd
&& !wndThis
)
984 hWnd
= ::GetParent(hWnd
);
985 wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
);
988 // Try translations first; find the youngest window with
989 // a translation table.
990 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
992 if ( wnd
->MSWTranslateMessage(wxmsg
) )
996 // Anyone for a non-translation message? Try youngest descendants first.
997 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
999 if ( wnd
->MSWProcessMessage(wxmsg
) )
1006 void wxApp::OnIdle(wxIdleEvent
& event
)
1008 static bool s_inOnIdle
= FALSE
;
1010 // Avoid recursion (via ProcessEvent default case)
1016 // 'Garbage' collection of windows deleted with Close().
1017 DeletePendingObjects();
1020 // flush the logged messages if any
1021 wxLog
*pLog
= wxLog::GetActiveTarget();
1022 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
1026 // Send OnIdle events to all windows
1027 if ( SendIdleEvents() )
1029 // SendIdleEvents() returns TRUE if at least one window requested more
1031 event
.RequestMore(TRUE
);
1034 // If they are pending events, we must process them: pending events are
1035 // either events to the threads other than main or events posted with
1036 // wxPostEvent() functions
1037 ProcessPendingEvents();
1042 // Send idle event to all top-level windows
1043 bool wxApp::SendIdleEvents()
1045 bool needMore
= FALSE
;
1047 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1050 wxWindow
* win
= node
->GetData();
1051 if (SendIdleEvents(win
))
1053 node
= node
->GetNext();
1059 // Send idle event to window and all subwindows
1060 bool wxApp::SendIdleEvents(wxWindow
* win
)
1062 bool needMore
= FALSE
;
1065 event
.SetEventObject(win
);
1066 win
->GetEventHandler()->ProcessEvent(event
);
1068 if (event
.MoreRequested())
1071 wxNode
* node
= win
->GetChildren().First();
1074 wxWindow
* win
= (wxWindow
*) node
->Data();
1075 if (SendIdleEvents(win
))
1078 node
= node
->Next();
1083 void wxApp::DeletePendingObjects()
1085 wxNode
*node
= wxPendingDelete
.First();
1088 wxObject
*obj
= (wxObject
*)node
->Data();
1092 if (wxPendingDelete
.Member(obj
))
1095 // Deleting one object may have deleted other pending
1096 // objects, so start from beginning of list again.
1097 node
= wxPendingDelete
.First();
1101 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1104 GetTopWindow()->Close(TRUE
);
1107 // Default behaviour: close the application with prompts. The
1108 // user can veto the close, and therefore the end session.
1109 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1113 if (!GetTopWindow()->Close(!event
.CanVeto()))
1121 bool wxApp::InitRichEdit(int version
)
1123 wxCHECK_MSG( version
>= 1 && version
<= 3, FALSE
,
1124 _T("incorrect richedit control version requested") );
1126 if ( version
<= gs_verRichEdit
)
1128 // we've already got this or better
1134 ::FreeLibrary(gs_hRichEdit
);
1137 // always try load riched20.dll first - like this we won't have to reload
1138 // it later if we're first asked for RE 1 and then for RE 2 or 3
1139 wxString dllname
= _T("riched20.dll");
1140 gs_hRichEdit
= ::LoadLibrary(dllname
);
1141 if ( !gs_hRichEdit
&& (version
== 1) )
1143 // fall back to RE 1
1144 dllname
= _T("riched32.dll");
1145 gs_hRichEdit
= ::LoadLibrary(dllname
);
1148 if ( !gs_hRichEdit
)
1150 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname
.c_str());
1152 gs_verRichEdit
= -1;
1157 gs_verRichEdit
= version
;
1162 #endif // wxUSE_RICHEDIT
1165 int wxApp::GetComCtl32Version()
1168 static int s_verComCtl32
= -1;
1170 wxCRIT_SECT_DECLARE(csComCtl32
);
1171 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1173 if ( s_verComCtl32
== -1 )
1175 // initally assume no comctl32.dll at all
1179 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1181 // if so, then we can check for the version
1182 if ( hModuleComCtl32
)
1184 // try to use DllGetVersion() if available in _headers_
1185 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1186 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1187 ::GetProcAddress(hModuleComCtl32
, _T("DllGetVersion"));
1188 if ( pfnDllGetVersion
)
1191 dvi
.cbSize
= sizeof(dvi
);
1193 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1196 wxLogApiError(_T("DllGetVersion"), hr
);
1200 // this is incompatible with _WIN32_IE values, but
1201 // compatible with the other values returned by
1202 // GetComCtl32Version()
1203 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1208 // DllGetVersion() unavailable either during compile or
1209 // run-time, try to guess the version otherwise
1210 if ( !s_verComCtl32
)
1212 // InitCommonControlsEx is unique to 4.70 and later
1213 FARPROC theProc
= ::GetProcAddress
1216 _T("InitCommonControlsEx")
1221 // not found, must be 4.00
1222 s_verComCtl32
= 400;
1226 // many symbols appeared in comctl32 4.71, could use
1227 // any of them except may be DllInstall
1228 theProc
= ::GetProcAddress
1231 _T("InitializeFlatSB")
1235 // not found, must be 4.70
1236 s_verComCtl32
= 470;
1240 // found, must be 4.71
1241 s_verComCtl32
= 471;
1248 return s_verComCtl32
;
1253 wxLogError(_("Fatal error: exiting"));
1258 // Yield to incoming messages
1261 // we don't want to process WM_QUIT from here - it should be processed in
1262 // the main event loop in order to stop it
1265 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1266 msg
.message
!= WM_QUIT
)
1268 if ( !wxTheApp
->DoMessage() )
1272 // If they are pending events, we must process them.
1273 wxTheApp
->ProcessPendingEvents();
1278 //-----------------------------------------------------------------------------
1280 //-----------------------------------------------------------------------------
1284 // Send the top window a dummy message so idle handler processing will
1285 // start up again. Doing it this way ensures that the idle handler
1286 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1287 // the same for the main app thread only)
1288 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1291 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1293 // should never happen
1294 wxLogLastError("PostMessage(WM_NULL)");
1299 //-----------------------------------------------------------------------------
1302 wxApp::GetStdIcon(int which
) const
1306 case wxICON_INFORMATION
:
1307 return wxIcon("wxICON_INFO");
1309 case wxICON_QUESTION
:
1310 return wxIcon("wxICON_QUESTION");
1312 case wxICON_EXCLAMATION
:
1313 return wxIcon("wxICON_WARNING");
1316 wxFAIL_MSG(wxT("requested non existent standard icon"));
1317 // still fall through
1320 return wxIcon("wxICON_ERROR");
1324 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1325 // if in a separate file. So include it here to ensure it's linked.
1326 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))