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 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
172 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
173 EVT_IDLE(wxApp::OnIdle
)
174 EVT_END_SESSION(wxApp::OnEndSession
)
175 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
179 bool wxApp::Initialize()
181 // Some people may wish to use this, but
182 // probably it shouldn't be here by default.
184 // wxRedirectIOToConsole();
187 wxBuffer
= new wxChar
[1500]; // FIXME
189 wxClassInfo::InitializeClasses();
192 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
196 wxPendingEventsLocker
= new wxCriticalSection
;
199 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
200 wxTheColourDatabase
->Initialize();
202 wxInitializeStockLists();
203 wxInitializeStockObjects();
205 #if wxUSE_WX_RESOURCES
206 wxInitializeResourceSystem();
209 wxBitmap::InitStandardHandlers();
211 #if defined(__WIN95__)
212 InitCommonControls();
219 // for OLE, enlarge message queue to be as large as possible
221 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
224 // we need to initialize OLE library
225 if ( FAILED(::OleInitialize(NULL
)) )
226 wxLogError(_("Cannot initialize OLE"));
230 if (!Ctl3dRegister(wxhInstance
))
231 wxLogError(wxT("Cannot register CTL3D"));
233 Ctl3dAutoSubclass(wxhInstance
);
236 g_globalCursor
= new wxCursor
;
238 // VZ: these icons are not in wx.rc anyhow (but should they?)!
240 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
241 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
242 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
244 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
245 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
246 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
249 RegisterWindowClasses();
251 // Create the brush for disabling bitmap buttons
254 lb
.lbStyle
= BS_PATTERN
;
255 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
258 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
259 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
261 //else: wxWindows resources are probably not linked in
267 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
269 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
270 // PLEASE DO NOT ALTER THIS.
271 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
272 extern char wxDummyChar
;
273 if (wxDummyChar
) wxDummyChar
++;
276 wxSetKeyboardHook(TRUE
);
278 wxModule::RegisterModules();
279 if (!wxModule::InitializeModules())
284 // ---------------------------------------------------------------------------
285 // RegisterWindowClasses
286 // ---------------------------------------------------------------------------
288 // TODO we should only register classes really used by the app. For this it
289 // would be enough to just delay the class registration until an attempt
290 // to create a window of this class is made.
291 bool wxApp::RegisterWindowClasses()
295 // for each class we register one with CS_(V|H)REDRAW style and one
296 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
297 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
298 static const long styleNoRedraw
= CS_DBLCLKS
;
300 // the fields which are common to all classes
301 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
302 wndclass
.cbClsExtra
= 0;
303 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
304 wndclass
.hInstance
= wxhInstance
;
305 wndclass
.hIcon
= (HICON
) NULL
;
306 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
307 wndclass
.lpszMenuName
= NULL
;
309 // Register the frame window class.
310 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
311 wndclass
.lpszClassName
= wxFrameClassName
;
312 wndclass
.style
= styleNormal
;
314 if ( !RegisterClass(&wndclass
) )
316 wxLogLastError("RegisterClass(frame)");
322 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
323 wndclass
.style
= styleNoRedraw
;
325 if ( !RegisterClass(&wndclass
) )
327 wxLogLastError("RegisterClass(no redraw frame)");
332 // Register the MDI frame window class.
333 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
334 wndclass
.lpszClassName
= wxMDIFrameClassName
;
335 wndclass
.style
= styleNormal
;
337 if ( !RegisterClass(&wndclass
) )
339 wxLogLastError("RegisterClass(MDI parent)");
344 // "no redraw" MDI frame
345 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
346 wndclass
.style
= styleNoRedraw
;
348 if ( !RegisterClass(&wndclass
) )
350 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
355 // Register the MDI child frame window class.
356 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
357 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
358 wndclass
.style
= styleNormal
;
360 if ( !RegisterClass(&wndclass
) )
362 wxLogLastError("RegisterClass(MDI child)");
367 // "no redraw" MDI child frame
368 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
369 wndclass
.style
= styleNoRedraw
;
371 if ( !RegisterClass(&wndclass
) )
373 wxLogLastError("RegisterClass(no redraw MDI child)");
378 // Register the panel window class.
379 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
380 wndclass
.lpszClassName
= wxPanelClassName
;
381 wndclass
.style
= styleNormal
;
383 if ( !RegisterClass(&wndclass
) )
385 wxLogLastError("RegisterClass(panel)");
390 // Register the canvas and textsubwindow class name
391 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
392 wndclass
.lpszClassName
= wxCanvasClassName
;
394 if ( !RegisterClass(&wndclass
) )
396 wxLogLastError("RegisterClass(canvas)");
404 // ---------------------------------------------------------------------------
405 // Convert Windows to argc, argv style
406 // ---------------------------------------------------------------------------
408 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
412 wxString
cmdLine(lpCmdLine
);
415 // Get application name
416 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
417 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
422 wxStrcpy(name
, wxFileNameFromPath(name
));
423 wxStripExtension(name
);
424 wxTheApp
->SetAppName(name
);
427 // Treat strings enclosed in double-quotes as single arguments
429 int len
= cmdLine
.Length();
433 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
438 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
442 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
445 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
451 i
++; // Skip past 2nd quote
453 else // Unquoted argument
456 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
459 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
467 wxTheApp
->argv
= new wxChar
*[count
+ 1];
468 for (i
= 0; i
< count
; i
++)
470 wxString
arg(args
[i
]);
471 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
473 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
474 wxTheApp
->argc
= count
;
477 //// Cleans up any wxWindows internal structures left lying around
479 void wxApp::CleanUp()
484 // flush the logged messages if any and install a 'safer' log target: the
485 // default one (wxLogGui) can't be used after the resources are freed just
486 // below and the user suppliedo ne might be even more unsafe (using any
487 // wxWindows GUI function is unsafe starting from now)
488 wxLog::DontCreateOnDemand();
490 // this will flush the old messages if any
491 delete wxLog::SetActiveTarget(new wxLogStderr
);
494 // One last chance for pending objects to be cleaned up
495 wxTheApp
->DeletePendingObjects();
497 wxModule::CleanUpModules();
499 #if wxUSE_WX_RESOURCES
500 wxCleanUpResourceSystem();
502 // wxDefaultResourceTable->ClearTable();
505 // Indicate that the cursor can be freed, so that cursor won't be deleted
506 // by deleting the bitmap list before g_globalCursor goes out of scope
507 // (double deletion of the cursor).
508 wxSetCursor(wxNullCursor
);
509 delete g_globalCursor
;
510 g_globalCursor
= NULL
;
512 wxDeleteStockObjects();
514 // Destroy all GDI lists, etc.
515 wxDeleteStockLists();
517 delete wxTheColourDatabase
;
518 wxTheColourDatabase
= NULL
;
520 wxBitmap::CleanUpHandlers();
525 //// WINDOWS-SPECIFIC CLEANUP
527 wxSetKeyboardHook(FALSE
);
530 if (gs_hRichEdit
!= (HINSTANCE
) NULL
)
531 FreeLibrary(gs_hRichEdit
);
538 if (wxSTD_FRAME_ICON
)
539 DestroyIcon(wxSTD_FRAME_ICON
);
540 if (wxSTD_MDICHILDFRAME_ICON
)
541 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
542 if (wxSTD_MDIPARENTFRAME_ICON
)
543 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
545 if (wxDEFAULT_FRAME_ICON
)
546 DestroyIcon(wxDEFAULT_FRAME_ICON
);
547 if (wxDEFAULT_MDICHILDFRAME_ICON
)
548 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
549 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
550 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
552 if ( wxDisableButtonBrush
)
553 ::DeleteObject( wxDisableButtonBrush
);
560 Ctl3dUnregister(wxhInstance
);
564 delete wxWinHandleList
;
566 // GL: I'm annoyed ... I don't know where to put this and I don't want to
567 // create a module for that as it's part of the core.
568 delete wxPendingEvents
;
570 delete wxPendingEventsLocker
;
571 // If we don't do the following, we get an apparent memory leak.
572 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
575 wxClassInfo::CleanUpClasses();
580 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
581 // At this point we want to check if there are any memory
582 // blocks that aren't part of the wxDebugContext itself,
583 // as a special case. Then when dumping we need to ignore
584 // wxDebugContext, too.
585 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
587 wxLogDebug(wxT("There were memory leaks."));
588 wxDebugContext::Dump();
589 wxDebugContext::PrintStatistics();
591 // wxDebugContext::SetStream(NULL, NULL);
595 // do it as the very last thing because everything else can log messages
596 delete wxLog::SetActiveTarget(NULL
);
600 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
602 // temporarily disable this warning which would be generated in release builds
605 #pragma warning(disable: 4715) // not all control paths return a value
608 //// Main wxWindows entry point
609 int wxEntry(WXHINSTANCE hInstance
,
610 WXHINSTANCE
WXUNUSED(hPrevInstance
),
615 // do check for memory leaks on program exit
616 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
617 // deallocated memory which may be used to simulate low-memory condition)
618 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
620 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
621 // This seems to be necessary since there are 'rogue'
622 // objects present at this point (perhaps global objects?)
623 // Setting a checkpoint will ignore them as far as the
624 // memory checking facility is concerned.
625 // Of course you may argue that memory allocated in globals should be
626 // checked, but this is a reasonable compromise.
627 wxDebugContext::SetCheckpoint();
630 // take everything into a try-except block in release build
631 // FIXME other compilers must support Win32 SEH (structured exception
632 // handling) too, just find the appropriate keyword in their docs!
633 // Please note that it's _not_ the same as C++ exceptions!
634 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
635 #define CATCH_PROGRAM_EXCEPTIONS
639 #undef CATCH_PROGRAM_EXCEPTIONS
641 wxhInstance
= (HINSTANCE
) hInstance
;
643 if (!wxApp::Initialize())
646 // create the application object or ensure that one already exists
649 // The app may have declared a global application object, but we recommend
650 // the IMPLEMENT_APP macro is used instead, which sets an initializer
651 // function for delayed, dynamic app object construction.
652 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
653 wxT("No initializer - use IMPLEMENT_APP macro.") );
655 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
658 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
660 // save the WinMain() parameters
661 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
662 wxTheApp
->m_nCmdShow
= nCmdShow
;
664 // GUI-specific initialisation. In fact on Windows we don't have any,
665 // but this call is provided for compatibility across platforms.
666 wxTheApp
->OnInitGui();
668 // We really don't want timestamps by default, because it means
669 // we can't simply double-click on the error message and get to that
670 // line in the source. So VC++ at least, let's have a sensible default.
672 wxLog::SetTimestamp(NULL
);
677 if ( wxTheApp
->OnInit() )
681 retValue
= wxTheApp
->OnRun();
684 // We want to initialize, but not run or exit immediately.
687 //else: app initialization failed, so we skipped OnRun()
689 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
692 // Forcibly delete the window.
693 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
694 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
696 topWindow
->Close(TRUE
);
697 wxTheApp
->DeletePendingObjects();
702 wxTheApp
->SetTopWindow(NULL
);
712 #ifdef CATCH_PROGRAM_EXCEPTIONS
714 __except ( EXCEPTION_EXECUTE_HANDLER
) {
717 wxTheApp->OnFatalException();
720 // using wxLog would be unsafe here
722 _("Unrecoverable program error detected: "
723 " the application will terminate."),
725 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
727 ::ExitProcess(3); // the same exit code as abort()
731 #endif // CATCH_PROGRAM_EXCEPTIONS
734 // restore warning state
736 #pragma warning(default: 4715) // not all control paths return a value
741 //// Entry point for DLLs
743 int wxEntry(WXHINSTANCE hInstance
)
745 wxhInstance
= (HINSTANCE
) hInstance
;
748 // The app may have declared a global application object, but we recommend
749 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
750 // for delayed, dynamic app object construction.
753 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
754 "No initializer - use IMPLEMENT_APP macro." );
756 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
759 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
762 wxTheApp
->argv
= NULL
;
764 wxTheApp
->OnInitGui();
768 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
769 if ( topWindow
&& topWindow
->GetHWND())
771 topWindow
->Show(TRUE
);
778 //// Static member initialization
780 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
786 m_wantDebugOutput
= TRUE
;
790 m_printMode
= wxPRINT_WINDOWS
;
791 m_exitOnFrameDelete
= TRUE
;
797 // Delete command-line args
799 for (i
= 0; i
< argc
; i
++)
806 bool wxApp::Initialized()
814 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
820 * Get and process a message, returning FALSE if WM_QUIT
821 * received (and also set the flag telling the app to exit the main loop)
824 bool wxApp::DoMessage()
826 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
836 // should never happen, but let's test for it nevertheless
837 wxLogLastError("GetMessage");
842 wxASSERT_MSG( wxThread::IsMain(),
843 wxT("only the main thread can process Windows messages") );
845 static bool s_hadGuiLock
= TRUE
;
846 static wxMsgArray s_aSavedMessages
;
848 // if a secondary thread owns is doing GUI calls, save all messages for
849 // later processing - we can't process them right now because it will
850 // lead to recursive library calls (and we're not reentrant)
851 if ( !wxGuiOwnedByMainThread() )
853 s_hadGuiLock
= FALSE
;
855 // leave out WM_COMMAND messages: too dangerous, sometimes
856 // the message will be processed twice
857 if ( !wxIsWaitingForThread() ||
858 s_currentMsg
.message
!= WM_COMMAND
)
860 s_aSavedMessages
.Add(s_currentMsg
);
867 // have we just regained the GUI lock? if so, post all of the saved
870 // FIXME of course, it's not _exactly_ the same as processing the
871 // messages normally - expect some things to break...
876 size_t count
= s_aSavedMessages
.Count();
877 for ( size_t n
= 0; n
< count
; n
++ )
879 MSG
& msg
= s_aSavedMessages
[n
];
881 if ( !ProcessMessage((WXMSG
*)&msg
) )
883 ::TranslateMessage(&msg
);
884 ::DispatchMessage(&msg
);
888 s_aSavedMessages
.Empty();
891 #endif // wxUSE_THREADS
893 // Process the message
894 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
896 ::TranslateMessage(&s_currentMsg
);
897 ::DispatchMessage(&s_currentMsg
);
905 * Keep trying to process messages until WM_QUIT
908 * If there are messages to be processed, they will all be
909 * processed and OnIdle will not be called.
910 * When there are no more messages, OnIdle is called.
911 * If OnIdle requests more time,
912 * it will be repeatedly called so long as there are no pending messages.
913 * A 'feature' of this is that once OnIdle has decided that no more processing
914 * is required, then it won't get processing time until further messages
915 * are processed (it'll sit in DoMessage).
918 int wxApp::MainLoop()
922 while ( m_keepGoing
)
925 wxMutexGuiLeaveOrEnter();
926 #endif // wxUSE_THREADS
928 while ( !::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) &&
937 return s_currentMsg
.wParam
;
940 // Returns TRUE if more time is needed.
941 bool wxApp::ProcessIdle()
944 event
.SetEventObject(this);
947 return event
.MoreRequested();
950 void wxApp::ExitMainLoop()
955 bool wxApp::Pending()
957 return (::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0);
960 void wxApp::Dispatch()
966 * Give all windows a chance to preprocess
967 * the message. Some may have accelerator tables, or have
971 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
973 MSG
*msg
= (MSG
*)wxmsg
;
974 HWND hWnd
= msg
->hwnd
;
975 wxWindow
*wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
), *wnd
;
977 // for some composite controls (like a combobox), wndThis might be NULL
978 // because the subcontrol is not a wxWindow, but only the control itself
979 // is - try to catch this case
980 while ( hWnd
&& !wndThis
)
982 hWnd
= ::GetParent(hWnd
);
983 wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
);
986 // Try translations first; find the youngest window with
987 // a translation table.
988 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
990 if ( wnd
->MSWTranslateMessage(wxmsg
) )
994 // Anyone for a non-translation message? Try youngest descendants first.
995 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
997 if ( wnd
->MSWProcessMessage(wxmsg
) )
1004 void wxApp::OnIdle(wxIdleEvent
& event
)
1006 static bool s_inOnIdle
= FALSE
;
1008 // Avoid recursion (via ProcessEvent default case)
1014 // 'Garbage' collection of windows deleted with Close().
1015 DeletePendingObjects();
1018 // flush the logged messages if any
1019 wxLog
*pLog
= wxLog::GetActiveTarget();
1020 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
1024 // Send OnIdle events to all windows
1025 if ( SendIdleEvents() )
1027 // SendIdleEvents() returns TRUE if at least one window requested more
1029 event
.RequestMore(TRUE
);
1032 // If they are pending events, we must process them: pending events are
1033 // either events to the threads other than main or events posted with
1034 // wxPostEvent() functions
1035 ProcessPendingEvents();
1040 // Send idle event to all top-level windows
1041 bool wxApp::SendIdleEvents()
1043 bool needMore
= FALSE
;
1045 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1048 wxWindow
* win
= node
->GetData();
1049 if (SendIdleEvents(win
))
1051 node
= node
->GetNext();
1057 // Send idle event to window and all subwindows
1058 bool wxApp::SendIdleEvents(wxWindow
* win
)
1060 bool needMore
= FALSE
;
1063 event
.SetEventObject(win
);
1064 win
->GetEventHandler()->ProcessEvent(event
);
1066 if (event
.MoreRequested())
1069 wxNode
* node
= win
->GetChildren().First();
1072 wxWindow
* win
= (wxWindow
*) node
->Data();
1073 if (SendIdleEvents(win
))
1076 node
= node
->Next();
1081 void wxApp::DeletePendingObjects()
1083 wxNode
*node
= wxPendingDelete
.First();
1086 wxObject
*obj
= (wxObject
*)node
->Data();
1090 if (wxPendingDelete
.Member(obj
))
1093 // Deleting one object may have deleted other pending
1094 // objects, so start from beginning of list again.
1095 node
= wxPendingDelete
.First();
1099 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1102 GetTopWindow()->Close(TRUE
);
1105 // Default behaviour: close the application with prompts. The
1106 // user can veto the close, and therefore the end session.
1107 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1111 if (!GetTopWindow()->Close(!event
.CanVeto()))
1119 bool wxApp::InitRichEdit(int version
)
1121 wxCHECK_MSG( version
>= 1 && version
<= 3, FALSE
,
1122 _T("incorrect richedit control version requested") );
1124 if ( version
<= gs_verRichEdit
)
1126 // we've already got this or better
1132 ::FreeLibrary(gs_hRichEdit
);
1135 // always try load riched20.dll first - like this we won't have to reload
1136 // it later if we're first asked for RE 1 and then for RE 2 or 3
1137 wxString dllname
= _T("riched20.dll");
1138 gs_hRichEdit
= ::LoadLibrary(dllname
);
1139 if ( !gs_hRichEdit
&& (version
== 1) )
1141 // fall back to RE 1
1142 dllname
= _T("riched32.dll");
1143 gs_hRichEdit
= ::LoadLibrary(dllname
);
1146 if ( !gs_hRichEdit
)
1148 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname
.c_str());
1150 gs_verRichEdit
= -1;
1155 gs_verRichEdit
= version
;
1160 #endif // wxUSE_RICHEDIT
1163 int wxApp::GetComCtl32Version()
1166 static int s_verComCtl32
= -1;
1168 wxCRIT_SECT_DECLARE(csComCtl32
);
1169 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1171 if ( s_verComCtl32
== -1 )
1173 // initally assume no comctl32.dll at all
1177 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1179 // if so, then we can check for the version
1180 if ( hModuleComCtl32
)
1182 // try to use DllGetVersion() if available in _headers_
1183 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1184 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1185 ::GetProcAddress(hModuleComCtl32
, _T("DllGetVersion"));
1186 if ( pfnDllGetVersion
)
1189 dvi
.cbSize
= sizeof(dvi
);
1191 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1194 wxLogApiError(_T("DllGetVersion"), hr
);
1198 // this is incompatible with _WIN32_IE values, but
1199 // compatible with the other values returned by
1200 // GetComCtl32Version()
1201 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1206 // DllGetVersion() unavailable either during compile or
1207 // run-time, try to guess the version otherwise
1208 if ( !s_verComCtl32
)
1210 // InitCommonControlsEx is unique to 4.70 and later
1211 FARPROC theProc
= ::GetProcAddress
1214 _T("InitCommonControlsEx")
1219 // not found, must be 4.00
1220 s_verComCtl32
= 400;
1224 // many symbols appeared in comctl32 4.71, could use
1225 // any of them except may be DllInstall
1226 theProc
= ::GetProcAddress
1229 _T("InitializeFlatSB")
1233 // not found, must be 4.70
1234 s_verComCtl32
= 470;
1238 // found, must be 4.71
1239 s_verComCtl32
= 471;
1246 return s_verComCtl32
;
1251 wxLogError(_("Fatal error: exiting"));
1256 // Yield to incoming messages
1259 // we don't want to process WM_QUIT from here - it should be processed in
1260 // the main event loop in order to stop it
1263 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1264 msg
.message
!= WM_QUIT
)
1266 if ( !wxTheApp
->DoMessage() )
1270 // If they are pending events, we must process them.
1271 wxTheApp
->ProcessPendingEvents();
1276 //-----------------------------------------------------------------------------
1278 //-----------------------------------------------------------------------------
1282 // Send the top window a dummy message so idle handler processing will
1283 // start up again. Doing it this way ensures that the idle handler
1284 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1285 // the same for the main app thread only)
1286 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1289 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1291 // should never happen
1292 wxLogLastError("PostMessage(WM_NULL)");
1297 //-----------------------------------------------------------------------------
1300 wxApp::GetStdIcon(int which
) const
1304 case wxICON_INFORMATION
:
1305 return wxIcon("wxICON_INFO");
1307 case wxICON_QUESTION
:
1308 return wxIcon("wxICON_QUESTION");
1310 case wxICON_EXCLAMATION
:
1311 return wxIcon("wxICON_WARNING");
1314 wxFAIL_MSG(wxT("requested non existent standard icon"));
1315 // still fall through
1318 return wxIcon("wxICON_ERROR");
1322 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1323 // if in a separate file. So include it here to ensure it's linked.
1324 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))