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
68 #if wxUSE_WX_RESOURCES
69 #include "wx/resource.h"
73 #include "wx/tooltip.h"
74 #endif // wxUSE_TOOLTIPS
76 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
77 // compilers don't support it (missing headers, libs, ...)
78 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
82 #endif // broken compilers
91 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
95 #ifndef __WXMICROWIN__
96 #include "wx/msw/msvcrt.h"
99 // ----------------------------------------------------------------------------
100 // conditional compilation
101 // ----------------------------------------------------------------------------
103 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
104 // defined before) and shows us what common control features are available
105 // during the compile time (it doesn't mean that they will be available during
106 // the run-time, use GetComCtl32Version() to test for them!). The possible
109 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
110 // 0x0300 4.70 IE 3.x
111 // 0x0400 4.71 IE 4.0
112 // 0x0401 4.72 IE 4.01 and Win98
113 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
116 // minimal set of features by default
117 #define _WIN32_IE 0x0200
120 #if _WIN32_IE >= 0x0300 && \
121 (!defined(__MINGW32__) || wxCHECK_W32API_VERSION( 2, 0 )) && \
126 // ---------------------------------------------------------------------------
128 // ---------------------------------------------------------------------------
130 extern wxChar
*wxBuffer
;
131 extern wxList WXDLLEXPORT wxPendingDelete
;
132 #ifndef __WXMICROWIN__
133 extern void wxSetKeyboardHook(bool doIt
);
137 wxApp
*wxTheApp
= NULL
;
139 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
140 // with NR suffix - wxWindow::MSWCreate() supposes this
141 const wxChar
*wxCanvasClassName
= wxT("wxWindowClass");
142 const wxChar
*wxCanvasClassNameNR
= wxT("wxWindowClassNR");
143 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
144 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
145 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
146 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
148 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
149 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
150 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
152 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
153 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
154 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
156 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
158 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 #if wxUSE_WX_RESOURCES
229 wxInitializeResourceSystem();
232 wxBitmap::InitStandardHandlers();
234 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
235 InitCommonControls();
238 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
241 // for OLE, enlarge message queue to be as large as possible
243 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
248 // we need to initialize OLE library
249 if ( FAILED(::OleInitialize(NULL
)) )
250 wxLogError(_("Cannot initialize OLE"));
256 if (!Ctl3dRegister(wxhInstance
))
257 wxLogError(wxT("Cannot register CTL3D"));
259 Ctl3dAutoSubclass(wxhInstance
);
260 #endif // wxUSE_CTL3D
262 // VZ: these icons are not in wx.rc anyhow (but should they?)!
264 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
265 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
266 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
268 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
269 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
270 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
273 RegisterWindowClasses();
275 #ifndef __WXMICROWIN__
276 // Create the brush for disabling bitmap buttons
279 lb
.lbStyle
= BS_PATTERN
;
281 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
284 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
285 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
287 //else: wxWindows resources are probably not linked in
294 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
296 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
297 // PLEASE DO NOT ALTER THIS.
298 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
299 extern char wxDummyChar
;
300 if (wxDummyChar
) wxDummyChar
++;
303 #ifndef __WXMICROWIN__
304 wxSetKeyboardHook(TRUE
);
307 wxModule::RegisterModules();
308 if (!wxModule::InitializeModules())
313 // ---------------------------------------------------------------------------
314 // RegisterWindowClasses
315 // ---------------------------------------------------------------------------
317 // TODO we should only register classes really used by the app. For this it
318 // would be enough to just delay the class registration until an attempt
319 // to create a window of this class is made.
320 bool wxApp::RegisterWindowClasses()
323 wxZeroMemory(wndclass
);
325 // for each class we register one with CS_(V|H)REDRAW style and one
326 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
327 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
328 static const long styleNoRedraw
= CS_DBLCLKS
;
330 // the fields which are common to all classes
331 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
332 wndclass
.hInstance
= wxhInstance
;
333 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
335 // Register the frame window class.
336 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
337 wndclass
.lpszClassName
= wxCanvasClassName
;
338 wndclass
.style
= styleNormal
;
340 if ( !RegisterClass(&wndclass
) )
342 wxLogLastError(wxT("RegisterClass(frame)"));
346 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
347 wndclass
.style
= styleNoRedraw
;
349 if ( !RegisterClass(&wndclass
) )
351 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
354 // Register the MDI frame window class.
355 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
356 wndclass
.lpszClassName
= wxMDIFrameClassName
;
357 wndclass
.style
= styleNormal
;
359 if ( !RegisterClass(&wndclass
) )
361 wxLogLastError(wxT("RegisterClass(MDI parent)"));
364 // "no redraw" MDI frame
365 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
366 wndclass
.style
= styleNoRedraw
;
368 if ( !RegisterClass(&wndclass
) )
370 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
373 // Register the MDI child frame window class.
374 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
375 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
376 wndclass
.style
= styleNormal
;
378 if ( !RegisterClass(&wndclass
) )
380 wxLogLastError(wxT("RegisterClass(MDI child)"));
383 // "no redraw" MDI child frame
384 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
385 wndclass
.style
= styleNoRedraw
;
387 if ( !RegisterClass(&wndclass
) )
389 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
395 // ---------------------------------------------------------------------------
396 // UnregisterWindowClasses
397 // ---------------------------------------------------------------------------
399 bool wxApp::UnregisterWindowClasses()
403 #ifndef __WXMICROWIN__
404 // MDI frame window class.
405 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
407 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
412 // "no redraw" MDI frame
413 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
415 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
420 // MDI child frame window class.
421 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
423 wxLogLastError(wxT("UnregisterClass(MDI child)"));
428 // "no redraw" MDI child frame
429 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
431 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
437 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
439 wxLogLastError(wxT("UnregisterClass(canvas)"));
444 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
446 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
450 #endif // __WXMICROWIN__
455 // ---------------------------------------------------------------------------
456 // Convert Windows to argc, argv style
457 // ---------------------------------------------------------------------------
459 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
461 // break the command line in words
463 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
465 // +1 here for the program name
466 argc
= args
.GetCount() + 1;
468 // and +1 here for the terminating NULL
469 argv
= new wxChar
*[argc
+ 1];
471 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
472 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
474 // also set the app name from argv[0]
476 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
478 // but don't override the name already set by the user code, if any
479 if ( GetAppName().empty() )
482 // copy all the other arguments to wxApp::argv[]
483 for ( int i
= 1; i
< argc
; i
++ )
485 argv
[i
] = copystring(args
[i
- 1]);
488 // argv[] must be NULL-terminated
492 //// Cleans up any wxWindows internal structures left lying around
494 void wxApp::CleanUp()
499 // flush the logged messages if any and install a 'safer' log target: the
500 // default one (wxLogGui) can't be used after the resources are freed just
501 // below and the user suppliedo ne might be even more unsafe (using any
502 // wxWindows GUI function is unsafe starting from now)
503 wxLog::DontCreateOnDemand();
505 // this will flush the old messages if any
506 delete wxLog::SetActiveTarget(new wxLogStderr
);
509 // One last chance for pending objects to be cleaned up
510 wxTheApp
->DeletePendingObjects();
512 wxModule::CleanUpModules();
514 #if wxUSE_WX_RESOURCES
515 wxCleanUpResourceSystem();
517 // wxDefaultResourceTable->ClearTable();
520 wxDeleteStockObjects();
522 // Destroy all GDI lists, etc.
523 wxDeleteStockLists();
525 delete wxTheColourDatabase
;
526 wxTheColourDatabase
= NULL
;
528 wxBitmap::CleanUpHandlers();
533 //// WINDOWS-SPECIFIC CLEANUP
535 #ifndef __WXMICROWIN__
536 wxSetKeyboardHook(FALSE
);
543 if (wxSTD_FRAME_ICON
)
544 DestroyIcon(wxSTD_FRAME_ICON
);
545 if (wxSTD_MDICHILDFRAME_ICON
)
546 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
547 if (wxSTD_MDIPARENTFRAME_ICON
)
548 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
550 if (wxDEFAULT_FRAME_ICON
)
551 DestroyIcon(wxDEFAULT_FRAME_ICON
);
552 if (wxDEFAULT_MDICHILDFRAME_ICON
)
553 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
554 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
555 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
557 if ( wxDisableButtonBrush
)
558 ::DeleteObject( wxDisableButtonBrush
);
565 // for an EXE the classes are unregistered when it terminates but DLL may
566 // be loaded several times (load/unload/load) into the same process in
567 // which case the registration will fail after the first time if we don't
568 // unregister the classes now
569 UnregisterWindowClasses();
570 #endif // WXMAKINGDLL
573 Ctl3dUnregister(wxhInstance
);
576 delete wxWinHandleHash
;
578 // GL: I'm annoyed ... I don't know where to put this and I don't want to
579 // create a module for that as it's part of the core.
580 delete wxPendingEvents
;
583 delete wxPendingEventsLocker
;
584 // If we don't do the following, we get an apparent memory leak
586 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
587 #endif // wxUSE_VALIDATORS
588 #endif // wxUSE_THREADS
590 wxClassInfo::CleanUpClasses();
595 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
596 // At this point we want to check if there are any memory
597 // blocks that aren't part of the wxDebugContext itself,
598 // as a special case. Then when dumping we need to ignore
599 // wxDebugContext, too.
600 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
602 wxLogMessage(wxT("There were memory leaks."));
603 wxDebugContext::Dump();
604 wxDebugContext::PrintStatistics();
606 // wxDebugContext::SetStream(NULL, NULL);
610 // do it as the very last thing because everything else can log messages
611 delete wxLog::SetActiveTarget(NULL
);
615 //----------------------------------------------------------------------
616 // Entry point helpers, used by wxPython
617 //----------------------------------------------------------------------
619 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
621 return wxApp::Initialize();
624 int WXDLLEXPORT
wxEntryInitGui()
626 return wxTheApp
->OnInitGui();
629 void WXDLLEXPORT
wxEntryCleanup()
635 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
637 // temporarily disable this warning which would be generated in release builds
640 #pragma warning(disable: 4715) // not all control paths return a value
643 //----------------------------------------------------------------------
644 // Main wxWindows entry point
645 //----------------------------------------------------------------------
646 int wxEntry(WXHINSTANCE hInstance
,
647 WXHINSTANCE
WXUNUSED(hPrevInstance
),
652 // do check for memory leaks on program exit
653 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
654 // deallocated memory which may be used to simulate low-memory condition)
655 #ifndef __WXMICROWIN__
656 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
660 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
661 // This seems to be necessary since there are 'rogue'
662 // objects present at this point (perhaps global objects?)
663 // Setting a checkpoint will ignore them as far as the
664 // memory checking facility is concerned.
665 // Of course you may argue that memory allocated in globals should be
666 // checked, but this is a reasonable compromise.
667 wxDebugContext::SetCheckpoint();
671 // take everything into a try-except block to be able to call
672 // OnFatalException() if necessary
673 #if wxUSE_ON_FATAL_EXCEPTION
676 wxhInstance
= (HINSTANCE
) hInstance
;
678 if (!wxEntryStart(0,0))
681 // create the application object or ensure that one already exists
684 // The app may have declared a global application object, but we recommend
685 // the IMPLEMENT_APP macro is used instead, which sets an initializer
686 // function for delayed, dynamic app object construction.
687 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
688 wxT("No initializer - use IMPLEMENT_APP macro.") );
690 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
693 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
695 // save the WinMain() parameters
696 if (lpCmdLine
) // MicroWindows passes NULL
697 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
698 wxTheApp
->m_nCmdShow
= nCmdShow
;
700 // We really don't want timestamps by default, because it means
701 // we can't simply double-click on the error message and get to that
702 // line in the source. So VC++ at least, let's have a sensible default.
705 wxLog::SetTimestamp(NULL
);
707 #endif // __VISUALC__
710 int retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
721 // we want to initialize, but not run or exit immediately.
725 //else: app initialization failed, so we skipped OnRun()
727 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
730 // Forcibly delete the window.
731 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
732 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
734 topWindow
->Close(TRUE
);
735 wxTheApp
->DeletePendingObjects();
740 wxTheApp
->SetTopWindow(NULL
);
744 retValue
= wxTheApp
->OnExit();
750 #if wxUSE_ON_FATAL_EXCEPTION
752 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
753 : EXCEPTION_CONTINUE_SEARCH
) {
756 // give the user a chance to do something special about this
757 wxTheApp
->OnFatalException();
760 ::ExitProcess(3); // the same exit code as abort()
764 #endif // wxUSE_ON_FATAL_EXCEPTION
767 // restore warning state
769 #pragma warning(default: 4715) // not all control paths return a value
774 //----------------------------------------------------------------------
775 // Entry point for wxWindows + the App in a DLL
776 //----------------------------------------------------------------------
778 int wxEntry(WXHINSTANCE hInstance
)
780 wxhInstance
= (HINSTANCE
) hInstance
;
783 // The app may have declared a global application object, but we recommend
784 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
785 // for delayed, dynamic app object construction.
788 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
789 "No initializer - use IMPLEMENT_APP macro." );
791 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
794 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
797 wxTheApp
->argv
= NULL
;
803 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
804 if ( topWindow
&& topWindow
->GetHWND())
806 topWindow
->Show(TRUE
);
813 //// Static member initialization
815 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
821 m_printMode
= wxPRINT_WINDOWS
;
827 // Delete command-line args
829 for (i
= 0; i
< argc
; i
++)
836 bool wxApp::Initialized()
843 #else // Assume initialized if DLL (no way of telling)
849 * Get and process a message, returning FALSE if WM_QUIT
850 * received (and also set the flag telling the app to exit the main loop)
853 bool wxApp::DoMessage()
855 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
865 // should never happen, but let's test for it nevertheless
866 wxLogLastError(wxT("GetMessage"));
871 wxASSERT_MSG( wxThread::IsMain(),
872 wxT("only the main thread can process Windows messages") );
874 static bool s_hadGuiLock
= TRUE
;
875 static wxMsgArray s_aSavedMessages
;
877 // if a secondary thread owns is doing GUI calls, save all messages for
878 // later processing - we can't process them right now because it will
879 // lead to recursive library calls (and we're not reentrant)
880 if ( !wxGuiOwnedByMainThread() )
882 s_hadGuiLock
= FALSE
;
884 // leave out WM_COMMAND messages: too dangerous, sometimes
885 // the message will be processed twice
886 if ( !wxIsWaitingForThread() ||
887 s_currentMsg
.message
!= WM_COMMAND
)
889 s_aSavedMessages
.Add(s_currentMsg
);
896 // have we just regained the GUI lock? if so, post all of the saved
899 // FIXME of course, it's not _exactly_ the same as processing the
900 // messages normally - expect some things to break...
905 size_t count
= s_aSavedMessages
.GetCount();
906 for ( size_t n
= 0; n
< count
; n
++ )
908 MSG
& msg
= s_aSavedMessages
[n
];
910 DoMessage((WXMSG
*)&msg
);
913 s_aSavedMessages
.Empty();
916 #endif // wxUSE_THREADS
918 // Process the message
919 DoMessage((WXMSG
*)&s_currentMsg
);
925 void wxApp::DoMessage(WXMSG
*pMsg
)
927 if ( !ProcessMessage(pMsg
) )
929 ::TranslateMessage((MSG
*)pMsg
);
930 ::DispatchMessage((MSG
*)pMsg
);
935 * Keep trying to process messages until WM_QUIT
938 * If there are messages to be processed, they will all be
939 * processed and OnIdle will not be called.
940 * When there are no more messages, OnIdle is called.
941 * If OnIdle requests more time,
942 * it will be repeatedly called so long as there are no pending messages.
943 * A 'feature' of this is that once OnIdle has decided that no more processing
944 * is required, then it won't get processing time until further messages
945 * are processed (it'll sit in DoMessage).
948 int wxApp::MainLoop()
952 while ( m_keepGoing
)
955 wxMutexGuiLeaveOrEnter();
956 #endif // wxUSE_THREADS
958 while ( !Pending() && ProcessIdle() )
961 // a message came or no more idle processing to do
965 return s_currentMsg
.wParam
;
968 // Returns TRUE if more time is needed.
969 bool wxApp::ProcessIdle()
972 event
.SetEventObject(this);
975 return event
.MoreRequested();
978 void wxApp::ExitMainLoop()
980 // this will set m_keepGoing to FALSE a bit later
981 ::PostQuitMessage(0);
984 bool wxApp::Pending()
986 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
989 void wxApp::Dispatch()
995 * Give all windows a chance to preprocess
996 * the message. Some may have accelerator tables, or have
1000 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1002 MSG
*msg
= (MSG
*)wxmsg
;
1003 HWND hwnd
= msg
->hwnd
;
1004 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1006 // this may happen if the event occured in a standard modeless dialog (the
1007 // only example of which I know of is the find/replace dialog) - then call
1008 // IsDialogMessage() to make TAB navigation in it work
1011 // we need to find the dialog containing this control as
1012 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1013 // them) if we call it for the control itself
1014 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1016 hwnd
= ::GetParent(hwnd
);
1019 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1023 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1024 // popup the tooltip bubbles
1025 if ( (msg
->message
== WM_MOUSEMOVE
) )
1027 wxToolTip
*tt
= wndThis
->GetToolTip();
1030 tt
->RelayEvent(wxmsg
);
1033 #endif // wxUSE_TOOLTIPS
1035 // allow the window to prevent certain messages from being
1036 // translated/processed (this is currently used by wxTextCtrl to always
1037 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1038 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1043 // try translations first: the accelerators override everything
1046 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1048 if ( wnd
->MSWTranslateMessage(wxmsg
))
1051 // stop at first top level window, i.e. don't try to process the key
1052 // strokes originating in a dialog using the accelerators of the parent
1053 // frame - this doesn't make much sense
1054 if ( wnd
->IsTopLevel() )
1058 // now try the other hooks (kbd navigation is handled here): we start from
1059 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1061 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1063 if ( wnd
->MSWProcessMessage(wxmsg
) )
1067 // no special preprocessing for this message, dispatch it normally
1071 // this is a temporary hack and will be replaced by using wxEventLoop in the
1074 // it is needed to allow other event loops (currently only one: the modal
1075 // dialog one) to reset the OnIdle() semaphore because otherwise OnIdle()
1076 // wouldn't do anything while a modal dialog shown from OnIdle() call is shown.
1077 bool wxIsInOnIdleFlag
= FALSE
;
1079 void wxApp::OnIdle(wxIdleEvent
& event
)
1081 // Avoid recursion (via ProcessEvent default case)
1082 if ( wxIsInOnIdleFlag
)
1085 wxIsInOnIdleFlag
= TRUE
;
1087 // If there are pending events, we must process them: pending events
1088 // are either events to the threads other than main or events posted
1089 // with wxPostEvent() functions
1090 // GRG: I have moved this here so that all pending events are processed
1091 // before starting to delete any objects. This behaves better (in
1092 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1093 // behaviour. Changed Feb/2000 before 2.1.14
1094 ProcessPendingEvents();
1096 // 'Garbage' collection of windows deleted with Close().
1097 DeletePendingObjects();
1100 // flush the logged messages if any
1101 wxLog::FlushActive();
1104 #if wxUSE_DC_CACHEING
1105 // automated DC cache management: clear the cached DCs and bitmap
1106 // if it's likely that the app has finished with them, that is, we
1107 // get an idle event and we're not dragging anything.
1108 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1110 #endif // wxUSE_DC_CACHEING
1112 // Send OnIdle events to all windows
1113 if ( SendIdleEvents() )
1115 // SendIdleEvents() returns TRUE if at least one window requested more
1117 event
.RequestMore(TRUE
);
1120 wxIsInOnIdleFlag
= FALSE
;
1123 // Send idle event to all top-level windows
1124 bool wxApp::SendIdleEvents()
1126 bool needMore
= FALSE
;
1128 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1131 wxWindow
* win
= node
->GetData();
1132 if (SendIdleEvents(win
))
1134 node
= node
->GetNext();
1140 // Send idle event to window and all subwindows
1141 bool wxApp::SendIdleEvents(wxWindow
* win
)
1144 event
.SetEventObject(win
);
1145 win
->GetEventHandler()->ProcessEvent(event
);
1147 bool needMore
= event
.MoreRequested();
1149 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
1152 wxWindow
*win
= node
->GetData();
1153 if (SendIdleEvents(win
))
1156 node
= node
->GetNext();
1162 void wxApp::DeletePendingObjects()
1164 wxNode
*node
= wxPendingDelete
.GetFirst();
1167 wxObject
*obj
= node
->GetData();
1171 if (wxPendingDelete
.Member(obj
))
1174 // Deleting one object may have deleted other pending
1175 // objects, so start from beginning of list again.
1176 node
= wxPendingDelete
.GetFirst();
1180 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1183 GetTopWindow()->Close(TRUE
);
1186 // Default behaviour: close the application with prompts. The
1187 // user can veto the close, and therefore the end session.
1188 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1192 if (!GetTopWindow()->Close(!event
.CanVeto()))
1198 int wxApp::GetComCtl32Version()
1200 #ifdef __WXMICROWIN__
1204 static int s_verComCtl32
= -1;
1206 wxCRIT_SECT_DECLARE(csComCtl32
);
1207 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1209 if ( s_verComCtl32
== -1 )
1211 // initally assume no comctl32.dll at all
1215 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1217 // if so, then we can check for the version
1218 if ( hModuleComCtl32
)
1220 // try to use DllGetVersion() if available in _headers_
1221 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1222 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1223 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1224 if ( pfnDllGetVersion
)
1227 dvi
.cbSize
= sizeof(dvi
);
1229 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1232 wxLogApiError(_T("DllGetVersion"), hr
);
1236 // this is incompatible with _WIN32_IE values, but
1237 // compatible with the other values returned by
1238 // GetComCtl32Version()
1239 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1244 // DllGetVersion() unavailable either during compile or
1245 // run-time, try to guess the version otherwise
1246 if ( !s_verComCtl32
)
1248 // InitCommonControlsEx is unique to 4.70 and later
1249 FARPROC theProc
= ::GetProcAddress
1252 "InitCommonControlsEx"
1257 // not found, must be 4.00
1258 s_verComCtl32
= 400;
1262 // many symbols appeared in comctl32 4.71, could use
1263 // any of them except may be DllInstall
1264 theProc
= ::GetProcAddress
1271 // not found, must be 4.70
1272 s_verComCtl32
= 470;
1276 // found, must be 4.71
1277 s_verComCtl32
= 471;
1284 return s_verComCtl32
;
1290 wxLogError(_("Fatal error: exiting"));
1296 // Yield to incoming messages
1298 bool wxApp::Yield(bool onlyIfNeeded
)
1301 static bool s_inYield
= FALSE
;
1304 // disable log flushing from here because a call to wxYield() shouldn't
1305 // normally result in message boxes popping up &c
1311 if ( !onlyIfNeeded
)
1313 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1321 // we don't want to process WM_QUIT from here - it should be processed in
1322 // the main event loop in order to stop it
1324 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1325 msg
.message
!= WM_QUIT
)
1328 wxMutexGuiLeaveOrEnter();
1329 #endif // wxUSE_THREADS
1331 if ( !wxTheApp
->DoMessage() )
1335 // if there are pending events, we must process them.
1336 ProcessPendingEvents();
1339 // let the logs be flashed again
1348 bool wxHandleFatalExceptions(bool doit
)
1350 #if wxUSE_ON_FATAL_EXCEPTION
1351 // assume this can only be called from the main thread
1352 gs_handleExceptions
= doit
;
1356 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1363 //-----------------------------------------------------------------------------
1365 //-----------------------------------------------------------------------------
1369 // Send the top window a dummy message so idle handler processing will
1370 // start up again. Doing it this way ensures that the idle handler
1371 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1372 // the same for the main app thread only)
1373 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1376 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1378 // should never happen
1379 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1384 //-----------------------------------------------------------------------------
1386 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1387 // if in a separate file. So include it here to ensure it's linked.
1388 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__WINE__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))