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 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
132 // with NR suffix - wxWindow::MSWCreate() supposes this
133 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
134 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
135 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
136 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
137 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
138 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
139 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
140 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
142 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
143 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
144 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
146 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
147 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
148 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
150 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
152 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
155 // the handle to richedit DLL and the version of the DLL loaded
156 static HINSTANCE gs_hRichEdit
= (HINSTANCE
)NULL
;
157 static int gs_verRichEdit
= -1;
160 // ===========================================================================
162 // ===========================================================================
164 // ---------------------------------------------------------------------------
166 // ---------------------------------------------------------------------------
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
)
177 bool wxApp::Initialize()
179 // Some people may wish to use this, but
180 // probably it shouldn't be here by default.
182 // wxRedirectIOToConsole();
185 wxBuffer
= new wxChar
[1500]; // FIXME
187 wxClassInfo::InitializeClasses();
190 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
194 wxPendingEventsLocker
= new wxCriticalSection
;
197 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
198 wxTheColourDatabase
->Initialize();
200 wxInitializeStockLists();
201 wxInitializeStockObjects();
203 #if wxUSE_WX_RESOURCES
204 wxInitializeResourceSystem();
207 wxBitmap::InitStandardHandlers();
209 #if defined(__WIN95__)
210 InitCommonControls();
217 // for OLE, enlarge message queue to be as large as possible
219 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
222 // we need to initialize OLE library
223 if ( FAILED(::OleInitialize(NULL
)) )
224 wxLogError(_("Cannot initialize OLE"));
228 if (!Ctl3dRegister(wxhInstance
))
229 wxLogError(wxT("Cannot register CTL3D"));
231 Ctl3dAutoSubclass(wxhInstance
);
234 g_globalCursor
= new wxCursor
;
236 // VZ: these icons are not in wx.rc anyhow (but should they?)!
238 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
239 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
240 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
242 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
243 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
244 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
247 RegisterWindowClasses();
249 // Create the brush for disabling bitmap buttons
252 lb
.lbStyle
= BS_PATTERN
;
253 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
256 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
257 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
259 //else: wxWindows resources are probably not linked in
265 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
267 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
268 // PLEASE DO NOT ALTER THIS.
269 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
270 extern char wxDummyChar
;
271 if (wxDummyChar
) wxDummyChar
++;
274 wxSetKeyboardHook(TRUE
);
276 wxModule::RegisterModules();
277 if (!wxModule::InitializeModules())
282 // ---------------------------------------------------------------------------
283 // RegisterWindowClasses
284 // ---------------------------------------------------------------------------
286 // TODO we should only register classes really used by the app. For this it
287 // would be enough to just delay the class registration until an attempt
288 // to create a window of this class is made.
289 bool wxApp::RegisterWindowClasses()
293 // for each class we register one with CS_(V|H)REDRAW style and one
294 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
295 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
296 static const long styleNoRedraw
= CS_DBLCLKS
;
298 // the fields which are common to all classes
299 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
300 wndclass
.cbClsExtra
= 0;
301 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
302 wndclass
.hInstance
= wxhInstance
;
303 wndclass
.hIcon
= (HICON
) NULL
;
304 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
305 wndclass
.lpszMenuName
= NULL
;
307 // Register the frame window class.
308 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
309 wndclass
.lpszClassName
= wxFrameClassName
;
310 wndclass
.style
= styleNormal
;
312 if ( !RegisterClass(&wndclass
) )
314 wxLogLastError("RegisterClass(frame)");
320 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
321 wndclass
.style
= styleNoRedraw
;
323 if ( !RegisterClass(&wndclass
) )
325 wxLogLastError("RegisterClass(no redraw frame)");
330 // Register the MDI frame window class.
331 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
332 wndclass
.lpszClassName
= wxMDIFrameClassName
;
333 wndclass
.style
= styleNormal
;
335 if ( !RegisterClass(&wndclass
) )
337 wxLogLastError("RegisterClass(MDI parent)");
342 // "no redraw" MDI frame
343 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
344 wndclass
.style
= styleNoRedraw
;
346 if ( !RegisterClass(&wndclass
) )
348 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
353 // Register the MDI child frame window class.
354 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
355 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
356 wndclass
.style
= styleNormal
;
358 if ( !RegisterClass(&wndclass
) )
360 wxLogLastError("RegisterClass(MDI child)");
365 // "no redraw" MDI child frame
366 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
367 wndclass
.style
= styleNoRedraw
;
369 if ( !RegisterClass(&wndclass
) )
371 wxLogLastError("RegisterClass(no redraw MDI child)");
376 // Register the panel window class.
377 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
378 wndclass
.lpszClassName
= wxPanelClassName
;
379 wndclass
.style
= styleNormal
;
381 if ( !RegisterClass(&wndclass
) )
383 wxLogLastError("RegisterClass(panel)");
388 // Register the canvas and textsubwindow class name
389 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
390 wndclass
.lpszClassName
= wxCanvasClassName
;
392 if ( !RegisterClass(&wndclass
) )
394 wxLogLastError("RegisterClass(canvas)");
402 // ---------------------------------------------------------------------------
403 // Convert Windows to argc, argv style
404 // ---------------------------------------------------------------------------
406 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
410 wxString
cmdLine(lpCmdLine
);
413 // Get application name
414 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
415 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
420 wxStrcpy(name
, wxFileNameFromPath(name
));
421 wxStripExtension(name
);
422 wxTheApp
->SetAppName(name
);
425 // Treat strings enclosed in double-quotes as single arguments
427 int len
= cmdLine
.Length();
431 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
436 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
440 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
443 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
449 i
++; // Skip past 2nd quote
451 else // Unquoted argument
454 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
457 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
465 wxTheApp
->argv
= new wxChar
*[count
+ 1];
466 for (i
= 0; i
< count
; i
++)
468 wxString
arg(args
[i
]);
469 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
471 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
472 wxTheApp
->argc
= count
;
475 //// Cleans up any wxWindows internal structures left lying around
477 void wxApp::CleanUp()
482 // flush the logged messages if any and install a 'safer' log target: the
483 // default one (wxLogGui) can't be used after the resources are freed just
484 // below and the user suppliedo ne might be even more unsafe (using any
485 // wxWindows GUI function is unsafe starting from now)
486 wxLog::DontCreateOnDemand();
488 // this will flush the old messages if any
489 delete wxLog::SetActiveTarget(new wxLogStderr
);
492 // One last chance for pending objects to be cleaned up
493 wxTheApp
->DeletePendingObjects();
495 wxModule::CleanUpModules();
497 #if wxUSE_WX_RESOURCES
498 wxCleanUpResourceSystem();
500 // wxDefaultResourceTable->ClearTable();
503 // Indicate that the cursor can be freed, so that cursor won't be deleted
504 // by deleting the bitmap list before g_globalCursor goes out of scope
505 // (double deletion of the cursor).
506 wxSetCursor(wxNullCursor
);
507 delete g_globalCursor
;
508 g_globalCursor
= NULL
;
510 wxDeleteStockObjects();
512 // Destroy all GDI lists, etc.
513 wxDeleteStockLists();
515 delete wxTheColourDatabase
;
516 wxTheColourDatabase
= NULL
;
518 wxBitmap::CleanUpHandlers();
523 //// WINDOWS-SPECIFIC CLEANUP
525 wxSetKeyboardHook(FALSE
);
528 if (gs_hRichEdit
!= (HINSTANCE
) NULL
)
529 FreeLibrary(gs_hRichEdit
);
536 if (wxSTD_FRAME_ICON
)
537 DestroyIcon(wxSTD_FRAME_ICON
);
538 if (wxSTD_MDICHILDFRAME_ICON
)
539 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
540 if (wxSTD_MDIPARENTFRAME_ICON
)
541 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
543 if (wxDEFAULT_FRAME_ICON
)
544 DestroyIcon(wxDEFAULT_FRAME_ICON
);
545 if (wxDEFAULT_MDICHILDFRAME_ICON
)
546 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
547 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
548 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
550 if ( wxDisableButtonBrush
)
551 ::DeleteObject( wxDisableButtonBrush
);
558 Ctl3dUnregister(wxhInstance
);
562 delete wxWinHandleList
;
564 // GL: I'm annoyed ... I don't know where to put this and I don't want to
565 // create a module for that as it's part of the core.
566 delete wxPendingEvents
;
568 delete wxPendingEventsLocker
;
569 // If we don't do the following, we get an apparent memory leak.
570 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
573 wxClassInfo::CleanUpClasses();
578 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
579 // At this point we want to check if there are any memory
580 // blocks that aren't part of the wxDebugContext itself,
581 // as a special case. Then when dumping we need to ignore
582 // wxDebugContext, too.
583 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
585 wxLogDebug(wxT("There were memory leaks."));
586 wxDebugContext::Dump();
587 wxDebugContext::PrintStatistics();
589 // wxDebugContext::SetStream(NULL, NULL);
593 // do it as the very last thing because everything else can log messages
594 delete wxLog::SetActiveTarget(NULL
);
598 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
600 // temporarily disable this warning which would be generated in release builds
603 #pragma warning(disable: 4715) // not all control paths return a value
606 //// Main wxWindows entry point
607 int wxEntry(WXHINSTANCE hInstance
,
608 WXHINSTANCE
WXUNUSED(hPrevInstance
),
613 // do check for memory leaks on program exit
614 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
615 // deallocated memory which may be used to simulate low-memory condition)
616 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
618 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
619 // This seems to be necessary since there are 'rogue'
620 // objects present at this point (perhaps global objects?)
621 // Setting a checkpoint will ignore them as far as the
622 // memory checking facility is concerned.
623 // Of course you may argue that memory allocated in globals should be
624 // checked, but this is a reasonable compromise.
625 wxDebugContext::SetCheckpoint();
628 // take everything into a try-except block in release build
629 // FIXME other compilers must support Win32 SEH (structured exception
630 // handling) too, just find the appropriate keyword in their docs!
631 // Please note that it's _not_ the same as C++ exceptions!
632 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
633 #define CATCH_PROGRAM_EXCEPTIONS
637 #undef CATCH_PROGRAM_EXCEPTIONS
639 wxhInstance
= (HINSTANCE
) hInstance
;
641 if (!wxApp::Initialize())
644 // create the application object or ensure that one already exists
647 // The app may have declared a global application object, but we recommend
648 // the IMPLEMENT_APP macro is used instead, which sets an initializer
649 // function for delayed, dynamic app object construction.
650 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
651 wxT("No initializer - use IMPLEMENT_APP macro.") );
653 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
656 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
658 // save the WinMain() parameters
659 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
660 wxTheApp
->m_nCmdShow
= nCmdShow
;
662 // GUI-specific initialisation. In fact on Windows we don't have any,
663 // but this call is provided for compatibility across platforms.
664 wxTheApp
->OnInitGui();
666 // We really don't want timestamps by default, because it means
667 // we can't simply double-click on the error message and get to that
668 // line in the source. So VC++ at least, let's have a sensible default.
670 wxLog::SetTimestamp(NULL
);
675 if ( wxTheApp
->OnInit() )
679 retValue
= wxTheApp
->OnRun();
682 // We want to initialize, but not run or exit immediately.
685 //else: app initialization failed, so we skipped OnRun()
687 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
690 // Forcibly delete the window.
691 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
692 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
694 topWindow
->Close(TRUE
);
695 wxTheApp
->DeletePendingObjects();
700 wxTheApp
->SetTopWindow(NULL
);
710 #ifdef CATCH_PROGRAM_EXCEPTIONS
712 __except ( EXCEPTION_EXECUTE_HANDLER
) {
715 wxTheApp->OnFatalException();
718 // using wxLog would be unsafe here
720 _("Unrecoverable program error detected: "
721 " the application will terminate."),
723 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
725 ::ExitProcess(3); // the same exit code as abort()
729 #endif // CATCH_PROGRAM_EXCEPTIONS
732 // restore warning state
734 #pragma warning(default: 4715) // not all control paths return a value
739 //// Entry point for DLLs
741 int wxEntry(WXHINSTANCE hInstance
)
743 wxhInstance
= (HINSTANCE
) hInstance
;
746 // The app may have declared a global application object, but we recommend
747 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
748 // for delayed, dynamic app object construction.
751 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
752 "No initializer - use IMPLEMENT_APP macro." );
754 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
757 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
760 wxTheApp
->argv
= NULL
;
762 wxTheApp
->OnInitGui();
766 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
767 if ( topWindow
&& topWindow
->GetHWND())
769 topWindow
->Show(TRUE
);
776 //// Static member initialization
778 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
784 m_wantDebugOutput
= TRUE
;
788 m_printMode
= wxPRINT_WINDOWS
;
789 m_exitOnFrameDelete
= TRUE
;
795 // Delete command-line args
797 for (i
= 0; i
< argc
; i
++)
804 bool wxApp::Initialized()
812 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
818 * Get and process a message, returning FALSE if WM_QUIT
819 * received (and also set the flag telling the app to exit the main loop)
822 bool wxApp::DoMessage()
824 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
834 // should never happen, but let's test for it nevertheless
835 wxLogLastError("GetMessage");
840 wxASSERT_MSG( wxThread::IsMain(),
841 wxT("only the main thread can process Windows messages") );
843 static bool s_hadGuiLock
= TRUE
;
844 static wxMsgArray s_aSavedMessages
;
846 // if a secondary thread owns is doing GUI calls, save all messages for
847 // later processing - we can't process them right now because it will
848 // lead to recursive library calls (and we're not reentrant)
849 if ( !wxGuiOwnedByMainThread() )
851 s_hadGuiLock
= FALSE
;
853 // leave out WM_COMMAND messages: too dangerous, sometimes
854 // the message will be processed twice
855 if ( !wxIsWaitingForThread() ||
856 s_currentMsg
.message
!= WM_COMMAND
)
858 s_aSavedMessages
.Add(s_currentMsg
);
865 // have we just regained the GUI lock? if so, post all of the saved
868 // FIXME of course, it's not _exactly_ the same as processing the
869 // messages normally - expect some things to break...
874 size_t count
= s_aSavedMessages
.Count();
875 for ( size_t n
= 0; n
< count
; n
++ )
877 MSG
& msg
= s_aSavedMessages
[n
];
879 if ( !ProcessMessage((WXMSG
*)&msg
) )
881 ::TranslateMessage(&msg
);
882 ::DispatchMessage(&msg
);
886 s_aSavedMessages
.Empty();
889 #endif // wxUSE_THREADS
891 // Process the message
892 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
894 ::TranslateMessage(&s_currentMsg
);
895 ::DispatchMessage(&s_currentMsg
);
903 * Keep trying to process messages until WM_QUIT
906 * If there are messages to be processed, they will all be
907 * processed and OnIdle will not be called.
908 * When there are no more messages, OnIdle is called.
909 * If OnIdle requests more time,
910 * it will be repeatedly called so long as there are no pending messages.
911 * A 'feature' of this is that once OnIdle has decided that no more processing
912 * is required, then it won't get processing time until further messages
913 * are processed (it'll sit in DoMessage).
916 int wxApp::MainLoop()
920 while ( m_keepGoing
)
923 wxMutexGuiLeaveOrEnter();
924 #endif // wxUSE_THREADS
926 while ( !::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) &&
935 return s_currentMsg
.wParam
;
938 // Returns TRUE if more time is needed.
939 bool wxApp::ProcessIdle()
942 event
.SetEventObject(this);
945 return event
.MoreRequested();
948 void wxApp::ExitMainLoop()
953 bool wxApp::Pending()
955 return (::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0);
958 void wxApp::Dispatch()
964 * Give all windows a chance to preprocess
965 * the message. Some may have accelerator tables, or have
969 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
971 MSG
*msg
= (MSG
*)wxmsg
;
972 HWND hWnd
= msg
->hwnd
;
973 wxWindow
*wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
), *wnd
;
975 // for some composite controls (like a combobox), wndThis might be NULL
976 // because the subcontrol is not a wxWindow, but only the control itself
977 // is - try to catch this case
978 while ( hWnd
&& !wndThis
)
980 hWnd
= ::GetParent(hWnd
);
981 wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
);
984 // Try translations first; find the youngest window with
985 // a translation table.
986 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
988 if ( wnd
->MSWTranslateMessage(wxmsg
) )
992 // Anyone for a non-translation message? Try youngest descendants first.
993 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
995 if ( wnd
->MSWProcessMessage(wxmsg
) )
1002 void wxApp::OnIdle(wxIdleEvent
& event
)
1004 static bool s_inOnIdle
= FALSE
;
1006 // Avoid recursion (via ProcessEvent default case)
1012 // 'Garbage' collection of windows deleted with Close().
1013 DeletePendingObjects();
1016 // flush the logged messages if any
1017 wxLog
*pLog
= wxLog::GetActiveTarget();
1018 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
1022 // Send OnIdle events to all windows
1023 if ( SendIdleEvents() )
1025 // SendIdleEvents() returns TRUE if at least one window requested more
1027 event
.RequestMore(TRUE
);
1030 // If they are pending events, we must process them: pending events are
1031 // either events to the threads other than main or events posted with
1032 // wxPostEvent() functions
1033 ProcessPendingEvents();
1038 // Send idle event to all top-level windows
1039 bool wxApp::SendIdleEvents()
1041 bool needMore
= FALSE
;
1043 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1046 wxWindow
* win
= node
->GetData();
1047 if (SendIdleEvents(win
))
1049 node
= node
->GetNext();
1055 // Send idle event to window and all subwindows
1056 bool wxApp::SendIdleEvents(wxWindow
* win
)
1058 bool needMore
= FALSE
;
1061 event
.SetEventObject(win
);
1062 win
->GetEventHandler()->ProcessEvent(event
);
1064 if (event
.MoreRequested())
1067 wxNode
* node
= win
->GetChildren().First();
1070 wxWindow
* win
= (wxWindow
*) node
->Data();
1071 if (SendIdleEvents(win
))
1074 node
= node
->Next();
1079 void wxApp::DeletePendingObjects()
1081 wxNode
*node
= wxPendingDelete
.First();
1084 wxObject
*obj
= (wxObject
*)node
->Data();
1088 if (wxPendingDelete
.Member(obj
))
1091 // Deleting one object may have deleted other pending
1092 // objects, so start from beginning of list again.
1093 node
= wxPendingDelete
.First();
1097 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1100 GetTopWindow()->Close(TRUE
);
1103 // Default behaviour: close the application with prompts. The
1104 // user can veto the close, and therefore the end session.
1105 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1109 if (!GetTopWindow()->Close(!event
.CanVeto()))
1117 bool wxApp::InitRichEdit(int version
)
1119 wxCHECK_MSG( version
>= 1 && version
<= 3, FALSE
,
1120 _T("incorrect richedit control version requested") );
1122 if ( version
<= gs_verRichEdit
)
1124 // we've already got this or better
1130 ::FreeLibrary(gs_hRichEdit
);
1133 // always try load riched20.dll first - like this we won't have to reload
1134 // it later if we're first asked for RE 1 and then for RE 2 or 3
1135 wxString dllname
= _T("riched20.dll");
1136 gs_hRichEdit
= ::LoadLibrary(dllname
);
1137 if ( !gs_hRichEdit
&& (version
== 1) )
1139 // fall back to RE 1
1140 dllname
= _T("riched32.dll");
1141 gs_hRichEdit
= ::LoadLibrary(dllname
);
1144 if ( !gs_hRichEdit
)
1146 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname
.c_str());
1148 gs_verRichEdit
= -1;
1153 gs_verRichEdit
= version
;
1158 #endif // wxUSE_RICHEDIT
1161 int wxApp::GetComCtl32Version()
1164 static int s_verComCtl32
= -1;
1166 wxCRIT_SECT_DECLARE(csComCtl32
);
1167 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1169 if ( s_verComCtl32
== -1 )
1171 // initally assume no comctl32.dll at all
1175 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1177 // if so, then we can check for the version
1178 if ( hModuleComCtl32
)
1180 // try to use DllGetVersion() if available in _headers_
1181 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1182 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1183 ::GetProcAddress(hModuleComCtl32
, _T("DllGetVersion"));
1184 if ( pfnDllGetVersion
)
1187 dvi
.cbSize
= sizeof(dvi
);
1189 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1192 wxLogApiError(_T("DllGetVersion"), hr
);
1196 // this is incompatible with _WIN32_IE values, but
1197 // compatible with the other values returned by
1198 // GetComCtl32Version()
1199 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1204 // DllGetVersion() unavailable either during compile or
1205 // run-time, try to guess the version otherwise
1206 if ( !s_verComCtl32
)
1208 // InitCommonControlsEx is unique to 4.70 and later
1209 FARPROC theProc
= ::GetProcAddress
1212 _T("InitCommonControlsEx")
1217 // not found, must be 4.00
1218 s_verComCtl32
= 400;
1222 // many symbols appeared in comctl32 4.71, could use
1223 // any of them except may be DllInstall
1224 theProc
= ::GetProcAddress
1227 _T("InitializeFlatSB")
1231 // not found, must be 4.70
1232 s_verComCtl32
= 470;
1236 // found, must be 4.71
1237 s_verComCtl32
= 471;
1244 return s_verComCtl32
;
1249 wxLogError(_("Fatal error: exiting"));
1254 // Yield to incoming messages
1257 // we don't want to process WM_QUIT from here - it should be processed in
1258 // the main event loop in order to stop it
1261 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1262 msg
.message
!= WM_QUIT
)
1264 if ( !wxTheApp
->DoMessage() )
1268 // If they are pending events, we must process them.
1269 wxTheApp
->ProcessPendingEvents();
1274 //-----------------------------------------------------------------------------
1276 //-----------------------------------------------------------------------------
1280 // Send the top window a dummy message so idle handler processing will
1281 // start up again. Doing it this way ensures that the idle handler
1282 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1283 // the same for the main app thread only)
1284 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1287 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1289 // should never happen
1290 wxLogLastError("PostMessage(WM_NULL)");
1295 //-----------------------------------------------------------------------------
1298 wxApp::GetStdIcon(int which
) const
1302 case wxICON_INFORMATION
:
1303 return wxIcon("wxICON_INFO");
1305 case wxICON_QUESTION
:
1306 return wxIcon("wxICON_QUESTION");
1308 case wxICON_EXCLAMATION
:
1309 return wxIcon("wxICON_WARNING");
1312 wxFAIL_MSG(wxT("requested non existent standard icon"));
1313 // still fall through
1316 return wxIcon("wxICON_ERROR");
1320 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1321 // if in a separate file. So include it here to ensure it's linked.
1322 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))