1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
21 #pragma implementation "app.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
27 #if defined(__BORLANDC__)
35 #include "wx/gdicmn.h"
38 #include "wx/cursor.h"
40 #include "wx/palette.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
51 #include "wx/cmdline.h"
52 #include "wx/filename.h"
53 #include "wx/module.h"
55 #include "wx/msw/private.h"
58 #include "wx/thread.h"
60 // define the array of MSG strutures
61 WX_DECLARE_OBJARRAY(MSG
, wxMsgArray
);
63 #include "wx/arrimpl.cpp"
65 WX_DEFINE_OBJARRAY(wxMsgArray
);
66 #endif // wxUSE_THREADS
69 #include "wx/tooltip.h"
70 #endif // wxUSE_TOOLTIPS
72 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
73 // compilers don't support it (missing headers, libs, ...)
74 #if defined(__GNUWIN32_OLD__) || defined(__SYMANTEC__) || defined(__SALFORDC__)
78 #endif // broken compilers
87 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
91 #ifndef __WXMICROWIN__
92 #include "wx/msw/msvcrt.h"
95 // ----------------------------------------------------------------------------
96 // conditional compilation
97 // ----------------------------------------------------------------------------
99 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
100 // defined before) and shows us what common control features are available
101 // during the compile time (it doesn't mean that they will be available during
102 // the run-time, use GetComCtl32Version() to test for them!). The possible
105 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
106 // 0x0300 4.70 IE 3.x
107 // 0x0400 4.71 IE 4.0
108 // 0x0401 4.72 IE 4.01 and Win98
109 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
112 // minimal set of features by default
113 #define _WIN32_IE 0x0200
116 #if _WIN32_IE >= 0x0300 && \
117 (!defined(__MINGW32__) || wxCHECK_W32API_VERSION( 2, 0 )) && \
122 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 extern wxChar
*wxBuffer
;
127 extern wxList WXDLLEXPORT wxPendingDelete
;
128 #ifndef __WXMICROWIN__
129 extern void wxSetKeyboardHook(bool doIt
);
133 wxApp
*wxTheApp
= NULL
;
135 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
136 // with NR suffix - wxWindow::MSWCreate() supposes this
137 const wxChar
*wxCanvasClassName
= wxT("wxWindowClass");
138 const wxChar
*wxCanvasClassNameNR
= wxT("wxWindowClassNR");
139 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
140 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
141 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
142 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
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 #ifdef __DIGITALMARS__
155 extern "C" LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
157 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
160 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
161 // needs compiler support for Win32 SEH. Others (especially Borland)
162 // probably have it too, but I'm not sure about how it works
163 // JACS: get 'Cannot use __try in functions that require unwinding
164 // in Unicode mode, so disabling.
165 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
166 #undef wxUSE_ON_FATAL_EXCEPTION
167 #define wxUSE_ON_FATAL_EXCEPTION 0
170 #if wxUSE_ON_FATAL_EXCEPTION
171 static bool gs_handleExceptions
= FALSE
;
174 // ===========================================================================
176 // ===========================================================================
178 // ---------------------------------------------------------------------------
180 // ---------------------------------------------------------------------------
182 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
184 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
185 EVT_IDLE(wxApp::OnIdle
)
186 EVT_END_SESSION(wxApp::OnEndSession
)
187 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
191 bool wxApp::Initialize()
193 // the first thing to do is to check if we're trying to run an Unicode
194 // program under Win9x w/o MSLU emulation layer - if so, abort right now
195 // as it has no chance to work
196 #if wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
197 if ( wxGetOsVersion() != wxWINDOWS_NT
)
199 // note that we can use MessageBoxW() as it's implemented even under
200 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
201 // used by wxLocale are not
205 _T("This program uses Unicode and requires Windows NT/2000/XP.\nProgram aborted."),
206 _T("wxWindows Fatal Error"),
212 #endif // wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
214 wxBuffer
= new wxChar
[1500]; // FIXME
216 wxClassInfo::InitializeClasses();
219 wxPendingEventsLocker
= new wxCriticalSection
;
222 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
223 wxTheColourDatabase
->Initialize();
225 wxInitializeStockLists();
226 wxInitializeStockObjects();
228 wxBitmap::InitStandardHandlers();
230 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
231 InitCommonControls();
234 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
237 // for OLE, enlarge message queue to be as large as possible
239 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
244 // we need to initialize OLE library
245 if ( FAILED(::OleInitialize(NULL
)) )
246 wxLogError(_("Cannot initialize OLE"));
252 if (!Ctl3dRegister(wxhInstance
))
253 wxLogError(wxT("Cannot register CTL3D"));
255 Ctl3dAutoSubclass(wxhInstance
);
256 #endif // wxUSE_CTL3D
258 // VZ: these icons are not in wx.rc anyhow (but should they?)!
260 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
261 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
262 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
264 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
265 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
266 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
269 RegisterWindowClasses();
271 #ifndef __WXMICROWIN__
272 // Create the brush for disabling bitmap buttons
275 lb
.lbStyle
= BS_PATTERN
;
277 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
280 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
281 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
283 //else: wxWindows resources are probably not linked in
290 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
292 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
293 // PLEASE DO NOT ALTER THIS.
294 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
295 extern char wxDummyChar
;
296 if (wxDummyChar
) wxDummyChar
++;
299 #ifndef __WXMICROWIN__
300 wxSetKeyboardHook(TRUE
);
303 wxModule::RegisterModules();
304 if (!wxModule::InitializeModules())
309 // ---------------------------------------------------------------------------
310 // RegisterWindowClasses
311 // ---------------------------------------------------------------------------
313 // TODO we should only register classes really used by the app. For this it
314 // would be enough to just delay the class registration until an attempt
315 // to create a window of this class is made.
316 bool wxApp::RegisterWindowClasses()
319 wxZeroMemory(wndclass
);
321 // for each class we register one with CS_(V|H)REDRAW style and one
322 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
323 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
324 static const long styleNoRedraw
= CS_DBLCLKS
;
326 // the fields which are common to all classes
327 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
328 wndclass
.hInstance
= wxhInstance
;
329 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
331 // Register the frame window class.
332 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
333 wndclass
.lpszClassName
= wxCanvasClassName
;
334 wndclass
.style
= styleNormal
;
336 if ( !RegisterClass(&wndclass
) )
338 wxLogLastError(wxT("RegisterClass(frame)"));
342 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
343 wndclass
.style
= styleNoRedraw
;
345 if ( !RegisterClass(&wndclass
) )
347 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
350 // Register the MDI frame window class.
351 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
352 wndclass
.lpszClassName
= wxMDIFrameClassName
;
353 wndclass
.style
= styleNormal
;
355 if ( !RegisterClass(&wndclass
) )
357 wxLogLastError(wxT("RegisterClass(MDI parent)"));
360 // "no redraw" MDI frame
361 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
362 wndclass
.style
= styleNoRedraw
;
364 if ( !RegisterClass(&wndclass
) )
366 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
369 // Register the MDI child frame window class.
370 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
371 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
372 wndclass
.style
= styleNormal
;
374 if ( !RegisterClass(&wndclass
) )
376 wxLogLastError(wxT("RegisterClass(MDI child)"));
379 // "no redraw" MDI child frame
380 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
381 wndclass
.style
= styleNoRedraw
;
383 if ( !RegisterClass(&wndclass
) )
385 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
391 // ---------------------------------------------------------------------------
392 // UnregisterWindowClasses
393 // ---------------------------------------------------------------------------
395 bool wxApp::UnregisterWindowClasses()
399 #ifndef __WXMICROWIN__
400 // MDI frame window class.
401 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
403 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
408 // "no redraw" MDI frame
409 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
411 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
416 // MDI child frame window class.
417 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
419 wxLogLastError(wxT("UnregisterClass(MDI child)"));
424 // "no redraw" MDI child frame
425 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
427 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
433 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
435 wxLogLastError(wxT("UnregisterClass(canvas)"));
440 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
442 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
446 #endif // __WXMICROWIN__
451 // ---------------------------------------------------------------------------
452 // Convert Windows to argc, argv style
453 // ---------------------------------------------------------------------------
455 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
457 // break the command line in words
459 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
461 // +1 here for the program name
462 argc
= args
.GetCount() + 1;
464 // and +1 here for the terminating NULL
465 argv
= new wxChar
*[argc
+ 1];
467 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
468 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
470 // also set the app name from argv[0]
472 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
474 // but don't override the name already set by the user code, if any
475 if ( GetAppName().empty() )
478 // copy all the other arguments to wxApp::argv[]
479 for ( int i
= 1; i
< argc
; i
++ )
481 argv
[i
] = copystring(args
[i
- 1]);
484 // argv[] must be NULL-terminated
488 //// Cleans up any wxWindows internal structures left lying around
490 void wxApp::CleanUp()
495 // flush the logged messages if any and install a 'safer' log target: the
496 // default one (wxLogGui) can't be used after the resources are freed just
497 // below and the user suppliedo ne might be even more unsafe (using any
498 // wxWindows GUI function is unsafe starting from now)
499 wxLog::DontCreateOnDemand();
501 // this will flush the old messages if any
502 delete wxLog::SetActiveTarget(new wxLogStderr
);
505 // One last chance for pending objects to be cleaned up
506 wxTheApp
->DeletePendingObjects();
508 wxModule::CleanUpModules();
510 wxDeleteStockObjects();
512 // Destroy all GDI lists, etc.
513 wxDeleteStockLists();
515 delete wxTheColourDatabase
;
516 wxTheColourDatabase
= NULL
;
518 wxBitmap::CleanUpHandlers();
523 //// WINDOWS-SPECIFIC CLEANUP
525 #ifndef __WXMICROWIN__
526 wxSetKeyboardHook(FALSE
);
533 if (wxSTD_FRAME_ICON
)
534 DestroyIcon(wxSTD_FRAME_ICON
);
535 if (wxSTD_MDICHILDFRAME_ICON
)
536 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
537 if (wxSTD_MDIPARENTFRAME_ICON
)
538 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
540 if (wxDEFAULT_FRAME_ICON
)
541 DestroyIcon(wxDEFAULT_FRAME_ICON
);
542 if (wxDEFAULT_MDICHILDFRAME_ICON
)
543 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
544 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
545 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
547 if ( wxDisableButtonBrush
)
548 ::DeleteObject( wxDisableButtonBrush
);
555 // for an EXE the classes are unregistered when it terminates but DLL may
556 // be loaded several times (load/unload/load) into the same process in
557 // which case the registration will fail after the first time if we don't
558 // unregister the classes now
559 UnregisterWindowClasses();
560 #endif // WXMAKINGDLL
563 Ctl3dUnregister(wxhInstance
);
566 delete wxWinHandleHash
;
567 wxWinHandleHash
= NULL
; // Set to null in case anything later tries to ref it.
569 delete wxPendingEvents
;
570 wxPendingEvents
= NULL
; // Set to null because wxAppBase::wxEvtHandler is destroyed later.
573 delete wxPendingEventsLocker
;
574 wxPendingEventsLocker
= NULL
; // Set to null because wxAppBase::wxEvtHandler is destroyed later.
575 // If we don't do the following, we get an apparent memory leak
577 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
578 #endif // wxUSE_VALIDATORS
579 #endif // wxUSE_THREADS
581 wxClassInfo::CleanUpClasses();
586 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
587 // At this point we want to check if there are any memory
588 // blocks that aren't part of the wxDebugContext itself,
589 // as a special case. Then when dumping we need to ignore
590 // wxDebugContext, too.
591 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
593 wxLogMessage(wxT("There were memory leaks."));
594 wxDebugContext::Dump();
595 wxDebugContext::PrintStatistics();
597 // wxDebugContext::SetStream(NULL, NULL);
601 // do it as the very last thing because everything else can log messages
602 delete wxLog::SetActiveTarget(NULL
);
606 //----------------------------------------------------------------------
607 // Entry point helpers, used by wxPython
608 //----------------------------------------------------------------------
610 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
612 return wxApp::Initialize();
615 int WXDLLEXPORT
wxEntryInitGui()
617 return wxTheApp
->OnInitGui();
620 void WXDLLEXPORT
wxEntryCleanup()
626 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
628 // temporarily disable this warning which would be generated in release builds
631 #pragma warning(disable: 4715) // not all control paths return a value
634 //----------------------------------------------------------------------
635 // Main wxWindows entry point
636 //----------------------------------------------------------------------
637 int wxEntry(WXHINSTANCE hInstance
,
638 WXHINSTANCE
WXUNUSED(hPrevInstance
),
643 // do check for memory leaks on program exit
644 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
645 // deallocated memory which may be used to simulate low-memory condition)
646 #ifndef __WXMICROWIN__
647 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
651 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
652 // This seems to be necessary since there are 'rogue'
653 // objects present at this point (perhaps global objects?)
654 // Setting a checkpoint will ignore them as far as the
655 // memory checking facility is concerned.
656 // Of course you may argue that memory allocated in globals should be
657 // checked, but this is a reasonable compromise.
658 wxDebugContext::SetCheckpoint();
662 // take everything into a try-except block to be able to call
663 // OnFatalException() if necessary
664 #if wxUSE_ON_FATAL_EXCEPTION
667 wxhInstance
= (HINSTANCE
) hInstance
;
669 if (!wxEntryStart(0,0))
672 // create the application object or ensure that one already exists
675 // The app may have declared a global application object, but we recommend
676 // the IMPLEMENT_APP macro is used instead, which sets an initializer
677 // function for delayed, dynamic app object construction.
678 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
679 wxT("No initializer - use IMPLEMENT_APP macro.") );
681 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
684 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
686 // save the WinMain() parameters
687 if (lpCmdLine
) // MicroWindows passes NULL
688 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
689 wxTheApp
->m_nCmdShow
= nCmdShow
;
691 // We really don't want timestamps by default, because it means
692 // we can't simply double-click on the error message and get to that
693 // line in the source. So VC++ at least, let's have a sensible default.
696 wxLog::SetTimestamp(NULL
);
698 #endif // __VISUALC__
701 int retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
712 // we want to initialize, but not run or exit immediately.
716 //else: app initialization failed, so we skipped OnRun()
718 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
721 // Forcibly delete the window.
722 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
723 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
725 topWindow
->Close(TRUE
);
726 wxTheApp
->DeletePendingObjects();
731 wxTheApp
->SetTopWindow(NULL
);
735 retValue
= wxTheApp
->OnExit();
741 #if wxUSE_ON_FATAL_EXCEPTION
743 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
744 : EXCEPTION_CONTINUE_SEARCH
) {
747 // give the user a chance to do something special about this
748 wxTheApp
->OnFatalException();
751 ::ExitProcess(3); // the same exit code as abort()
755 #endif // wxUSE_ON_FATAL_EXCEPTION
758 // restore warning state
760 #pragma warning(default: 4715) // not all control paths return a value
765 //----------------------------------------------------------------------
766 // Entry point for wxWindows + the App in a DLL
767 //----------------------------------------------------------------------
769 int wxEntry(WXHINSTANCE hInstance
)
771 wxhInstance
= (HINSTANCE
) hInstance
;
774 // The app may have declared a global application object, but we recommend
775 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
776 // for delayed, dynamic app object construction.
779 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
780 "No initializer - use IMPLEMENT_APP macro." );
782 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
785 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
788 wxTheApp
->argv
= NULL
;
794 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
795 if ( topWindow
&& topWindow
->GetHWND())
797 topWindow
->Show(TRUE
);
804 //// Static member initialization
806 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
812 m_printMode
= wxPRINT_WINDOWS
;
818 // Delete command-line args
820 for (i
= 0; i
< argc
; i
++)
827 bool wxApp::Initialized()
834 #else // Assume initialized if DLL (no way of telling)
840 * Get and process a message, returning FALSE if WM_QUIT
841 * received (and also set the flag telling the app to exit the main loop)
844 bool wxApp::DoMessage()
846 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
856 // should never happen, but let's test for it nevertheless
857 wxLogLastError(wxT("GetMessage"));
862 wxASSERT_MSG( wxThread::IsMain(),
863 wxT("only the main thread can process Windows messages") );
865 static bool s_hadGuiLock
= TRUE
;
866 static wxMsgArray s_aSavedMessages
;
868 // if a secondary thread owns is doing GUI calls, save all messages for
869 // later processing - we can't process them right now because it will
870 // lead to recursive library calls (and we're not reentrant)
871 if ( !wxGuiOwnedByMainThread() )
873 s_hadGuiLock
= FALSE
;
875 // leave out WM_COMMAND messages: too dangerous, sometimes
876 // the message will be processed twice
877 if ( !wxIsWaitingForThread() ||
878 s_currentMsg
.message
!= WM_COMMAND
)
880 s_aSavedMessages
.Add(s_currentMsg
);
887 // have we just regained the GUI lock? if so, post all of the saved
890 // FIXME of course, it's not _exactly_ the same as processing the
891 // messages normally - expect some things to break...
896 size_t count
= s_aSavedMessages
.GetCount();
897 for ( size_t n
= 0; n
< count
; n
++ )
899 MSG
& msg
= s_aSavedMessages
[n
];
901 DoMessage((WXMSG
*)&msg
);
904 s_aSavedMessages
.Empty();
907 #endif // wxUSE_THREADS
909 // Process the message
910 DoMessage((WXMSG
*)&s_currentMsg
);
916 void wxApp::DoMessage(WXMSG
*pMsg
)
918 if ( !ProcessMessage(pMsg
) )
920 ::TranslateMessage((MSG
*)pMsg
);
921 ::DispatchMessage((MSG
*)pMsg
);
926 * Keep trying to process messages until WM_QUIT
929 * If there are messages to be processed, they will all be
930 * processed and OnIdle will not be called.
931 * When there are no more messages, OnIdle is called.
932 * If OnIdle requests more time,
933 * it will be repeatedly called so long as there are no pending messages.
934 * A 'feature' of this is that once OnIdle has decided that no more processing
935 * is required, then it won't get processing time until further messages
936 * are processed (it'll sit in DoMessage).
939 int wxApp::MainLoop()
943 while ( m_keepGoing
)
946 wxMutexGuiLeaveOrEnter();
947 #endif // wxUSE_THREADS
949 while ( !Pending() && ProcessIdle() )
952 // a message came or no more idle processing to do
956 return s_currentMsg
.wParam
;
959 // Returns TRUE if more time is needed.
960 bool wxApp::ProcessIdle()
963 event
.SetEventObject(this);
966 return event
.MoreRequested();
969 void wxApp::ExitMainLoop()
971 // this will set m_keepGoing to FALSE a bit later
972 ::PostQuitMessage(0);
975 bool wxApp::Pending()
977 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
980 void wxApp::Dispatch()
986 * Give all windows a chance to preprocess
987 * the message. Some may have accelerator tables, or have
991 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
993 MSG
*msg
= (MSG
*)wxmsg
;
994 HWND hwnd
= msg
->hwnd
;
995 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
997 // this may happen if the event occured in a standard modeless dialog (the
998 // only example of which I know of is the find/replace dialog) - then call
999 // IsDialogMessage() to make TAB navigation in it work
1002 // we need to find the dialog containing this control as
1003 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1004 // them) if we call it for the control itself
1005 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1007 hwnd
= ::GetParent(hwnd
);
1010 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1014 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1015 // popup the tooltip bubbles
1016 if ( (msg
->message
== WM_MOUSEMOVE
) )
1018 wxToolTip
*tt
= wndThis
->GetToolTip();
1021 tt
->RelayEvent(wxmsg
);
1024 #endif // wxUSE_TOOLTIPS
1026 // allow the window to prevent certain messages from being
1027 // translated/processed (this is currently used by wxTextCtrl to always
1028 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1029 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1034 // try translations first: the accelerators override everything
1037 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1039 if ( wnd
->MSWTranslateMessage(wxmsg
))
1042 // stop at first top level window, i.e. don't try to process the key
1043 // strokes originating in a dialog using the accelerators of the parent
1044 // frame - this doesn't make much sense
1045 if ( wnd
->IsTopLevel() )
1049 // now try the other hooks (kbd navigation is handled here): we start from
1050 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1052 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1054 if ( wnd
->MSWProcessMessage(wxmsg
) )
1058 // no special preprocessing for this message, dispatch it normally
1062 // this is a temporary hack and will be replaced by using wxEventLoop in the
1065 // it is needed to allow other event loops (currently only one: the modal
1066 // dialog one) to reset the OnIdle() semaphore because otherwise OnIdle()
1067 // wouldn't do anything while a modal dialog shown from OnIdle() call is shown.
1068 bool wxIsInOnIdleFlag
= FALSE
;
1070 void wxApp::OnIdle(wxIdleEvent
& event
)
1072 // Avoid recursion (via ProcessEvent default case)
1073 if ( wxIsInOnIdleFlag
)
1076 wxIsInOnIdleFlag
= TRUE
;
1078 // If there are pending events, we must process them: pending events
1079 // are either events to the threads other than main or events posted
1080 // with wxPostEvent() functions
1081 // GRG: I have moved this here so that all pending events are processed
1082 // before starting to delete any objects. This behaves better (in
1083 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1084 // behaviour. Changed Feb/2000 before 2.1.14
1085 ProcessPendingEvents();
1087 // 'Garbage' collection of windows deleted with Close().
1088 DeletePendingObjects();
1091 // flush the logged messages if any
1092 wxLog::FlushActive();
1095 #if wxUSE_DC_CACHEING
1096 // automated DC cache management: clear the cached DCs and bitmap
1097 // if it's likely that the app has finished with them, that is, we
1098 // get an idle event and we're not dragging anything.
1099 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1101 #endif // wxUSE_DC_CACHEING
1103 // Send OnIdle events to all windows
1104 if ( SendIdleEvents() )
1106 // SendIdleEvents() returns TRUE if at least one window requested more
1108 event
.RequestMore(TRUE
);
1111 wxIsInOnIdleFlag
= FALSE
;
1114 // Send idle event to all top-level windows
1115 bool wxApp::SendIdleEvents()
1117 bool needMore
= FALSE
;
1119 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1122 wxWindow
* win
= node
->GetData();
1123 if (SendIdleEvents(win
))
1125 node
= node
->GetNext();
1131 // Send idle event to window and all subwindows
1132 bool wxApp::SendIdleEvents(wxWindow
* win
)
1135 event
.SetEventObject(win
);
1136 win
->GetEventHandler()->ProcessEvent(event
);
1138 bool needMore
= event
.MoreRequested();
1140 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
1143 wxWindow
*win
= node
->GetData();
1144 if (SendIdleEvents(win
))
1147 node
= node
->GetNext();
1153 void wxApp::DeletePendingObjects()
1155 wxNode
*node
= wxPendingDelete
.GetFirst();
1158 wxObject
*obj
= node
->GetData();
1162 if (wxPendingDelete
.Member(obj
))
1165 // Deleting one object may have deleted other pending
1166 // objects, so start from beginning of list again.
1167 node
= wxPendingDelete
.GetFirst();
1171 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1174 GetTopWindow()->Close(TRUE
);
1177 // Default behaviour: close the application with prompts. The
1178 // user can veto the close, and therefore the end session.
1179 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1183 if (!GetTopWindow()->Close(!event
.CanVeto()))
1189 int wxApp::GetComCtl32Version()
1191 #ifdef __WXMICROWIN__
1195 static int s_verComCtl32
= -1;
1197 wxCRIT_SECT_DECLARE(csComCtl32
);
1198 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1200 if ( s_verComCtl32
== -1 )
1202 // initally assume no comctl32.dll at all
1206 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1208 // if so, then we can check for the version
1209 if ( hModuleComCtl32
)
1211 // try to use DllGetVersion() if available in _headers_
1212 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1213 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1214 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1215 if ( pfnDllGetVersion
)
1218 dvi
.cbSize
= sizeof(dvi
);
1220 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1223 wxLogApiError(_T("DllGetVersion"), hr
);
1227 // this is incompatible with _WIN32_IE values, but
1228 // compatible with the other values returned by
1229 // GetComCtl32Version()
1230 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1235 // DllGetVersion() unavailable either during compile or
1236 // run-time, try to guess the version otherwise
1237 if ( !s_verComCtl32
)
1239 // InitCommonControlsEx is unique to 4.70 and later
1240 FARPROC theProc
= ::GetProcAddress
1243 "InitCommonControlsEx"
1248 // not found, must be 4.00
1249 s_verComCtl32
= 400;
1253 // many symbols appeared in comctl32 4.71, could use
1254 // any of them except may be DllInstall
1255 theProc
= ::GetProcAddress
1262 // not found, must be 4.70
1263 s_verComCtl32
= 470;
1267 // found, must be 4.71
1268 s_verComCtl32
= 471;
1275 return s_verComCtl32
;
1283 wxTheApp
->ExitMainLoop();
1287 // what else can we do?
1292 // Yield to incoming messages
1294 bool wxApp::Yield(bool onlyIfNeeded
)
1297 static bool s_inYield
= FALSE
;
1300 // disable log flushing from here because a call to wxYield() shouldn't
1301 // normally result in message boxes popping up &c
1307 if ( !onlyIfNeeded
)
1309 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1317 // we don't want to process WM_QUIT from here - it should be processed in
1318 // the main event loop in order to stop it
1320 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1321 msg
.message
!= WM_QUIT
)
1324 wxMutexGuiLeaveOrEnter();
1325 #endif // wxUSE_THREADS
1327 if ( !wxTheApp
->DoMessage() )
1331 // if there are pending events, we must process them.
1332 ProcessPendingEvents();
1335 // let the logs be flashed again
1344 bool wxHandleFatalExceptions(bool doit
)
1346 #if wxUSE_ON_FATAL_EXCEPTION
1347 // assume this can only be called from the main thread
1348 gs_handleExceptions
= doit
;
1352 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1359 //-----------------------------------------------------------------------------
1361 //-----------------------------------------------------------------------------
1365 // Send the top window a dummy message so idle handler processing will
1366 // start up again. Doing it this way ensures that the idle handler
1367 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1368 // the same for the main app thread only)
1369 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1372 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1374 // should never happen
1375 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1380 //-----------------------------------------------------------------------------
1382 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1383 // if in a separate file. So include it here to ensure it's linked.
1384 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__WINE__) && !defined(WXMAKINGDLL))