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/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 && !defined(__MINGW32__)
124 // ---------------------------------------------------------------------------
126 // ---------------------------------------------------------------------------
128 extern wxChar
*wxBuffer
;
129 extern wxList WXDLLEXPORT wxPendingDelete
;
130 #ifndef __WXMICROWIN__
131 extern void wxSetKeyboardHook(bool doIt
);
135 wxApp
*wxTheApp
= NULL
;
137 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
138 // with NR suffix - wxWindow::MSWCreate() supposes this
139 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
140 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
141 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
142 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
143 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
144 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
145 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
146 const wxChar
*wxPanelClassNameNR
= wxT("wxPanelClassNR");
147 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
148 const wxChar
*wxCanvasClassNameNR
= wxT("wxCanvasClassNR");
150 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
151 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
152 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
154 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
155 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
156 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
158 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
160 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
162 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
163 // needs compiler support for Win32 SEH. Others (especially Borland)
164 // probably have it too, but I'm not sure about how it works
165 // JACS: get 'Cannot use __try in functions that require unwinding
166 // in Unicode mode, so disabling.
167 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
168 #undef wxUSE_ON_FATAL_EXCEPTION
169 #define wxUSE_ON_FATAL_EXCEPTION 0
172 #if wxUSE_ON_FATAL_EXCEPTION
173 static bool gs_handleExceptions
= FALSE
;
176 // ===========================================================================
178 // ===========================================================================
180 // ---------------------------------------------------------------------------
182 // ---------------------------------------------------------------------------
184 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
186 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
187 EVT_IDLE(wxApp::OnIdle
)
188 EVT_END_SESSION(wxApp::OnEndSession
)
189 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
193 bool wxApp::Initialize()
195 // the first thing to do is to check if we're trying to run an Unicode
196 // program under Win9x - if so, abort right now as it has no chance to
199 if ( wxGetOsVersion() != wxWINDOWS_NT
)
201 // note that we can use MessageBoxW() as it's implemented even under
202 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
203 // used by wxLocale are not
207 _T("This program uses Unicode and requires Windows NT/2000.\nProgram aborted."),
208 _T("wxWindows Fatal Error"),
214 #endif // wxUSE_UNICODE
216 // Some people may wish to use this, but
217 // probably it shouldn't be here by default.
219 // wxRedirectIOToConsole();
222 wxBuffer
= new wxChar
[1500]; // FIXME
224 wxClassInfo::InitializeClasses();
227 wxPendingEventsLocker
= new wxCriticalSection
;
230 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
231 wxTheColourDatabase
->Initialize();
233 wxInitializeStockLists();
234 wxInitializeStockObjects();
236 #if wxUSE_WX_RESOURCES
237 wxInitializeResourceSystem();
240 wxBitmap::InitStandardHandlers();
242 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
243 InitCommonControls();
246 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
249 // for OLE, enlarge message queue to be as large as possible
251 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
255 // we need to initialize OLE library
256 if ( FAILED(::OleInitialize(NULL
)) )
257 wxLogError(_("Cannot initialize OLE"));
262 if (!Ctl3dRegister(wxhInstance
))
263 wxLogError(wxT("Cannot register CTL3D"));
265 Ctl3dAutoSubclass(wxhInstance
);
266 #endif // wxUSE_CTL3D
268 // VZ: these icons are not in wx.rc anyhow (but should they?)!
270 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
271 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
272 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
274 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
275 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
276 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
279 RegisterWindowClasses();
281 #ifndef __WXMICROWIN__
282 // Create the brush for disabling bitmap buttons
285 lb
.lbStyle
= BS_PATTERN
;
287 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
290 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
291 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
293 //else: wxWindows resources are probably not linked in
300 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
302 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
303 // PLEASE DO NOT ALTER THIS.
304 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
305 extern char wxDummyChar
;
306 if (wxDummyChar
) wxDummyChar
++;
309 #ifndef __WXMICROWIN__
310 wxSetKeyboardHook(TRUE
);
313 wxModule::RegisterModules();
314 if (!wxModule::InitializeModules())
319 // ---------------------------------------------------------------------------
320 // RegisterWindowClasses
321 // ---------------------------------------------------------------------------
323 // TODO we should only register classes really used by the app. For this it
324 // would be enough to just delay the class registration until an attempt
325 // to create a window of this class is made.
326 bool wxApp::RegisterWindowClasses()
330 // for each class we register one with CS_(V|H)REDRAW style and one
331 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
332 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
333 static const long styleNoRedraw
= CS_DBLCLKS
;
335 // the fields which are common to all classes
336 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
337 wndclass
.cbClsExtra
= 0;
338 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
339 wndclass
.hInstance
= wxhInstance
;
340 wndclass
.hIcon
= (HICON
) NULL
;
341 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
342 wndclass
.lpszMenuName
= NULL
;
344 // Register the frame window class.
345 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
346 wndclass
.lpszClassName
= wxFrameClassName
;
347 wndclass
.style
= styleNormal
;
349 if ( !RegisterClass(&wndclass
) )
351 wxLogLastError(wxT("RegisterClass(frame)"));
357 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
358 wndclass
.style
= styleNoRedraw
;
360 if ( !RegisterClass(&wndclass
) )
362 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
367 // Register the MDI frame window class.
368 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
369 wndclass
.lpszClassName
= wxMDIFrameClassName
;
370 wndclass
.style
= styleNormal
;
372 if ( !RegisterClass(&wndclass
) )
374 wxLogLastError(wxT("RegisterClass(MDI parent)"));
379 // "no redraw" MDI frame
380 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
381 wndclass
.style
= styleNoRedraw
;
383 if ( !RegisterClass(&wndclass
) )
385 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
390 // Register the MDI child frame window class.
391 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
392 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
393 wndclass
.style
= styleNormal
;
395 if ( !RegisterClass(&wndclass
) )
397 wxLogLastError(wxT("RegisterClass(MDI child)"));
402 // "no redraw" MDI child frame
403 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
404 wndclass
.style
= styleNoRedraw
;
406 if ( !RegisterClass(&wndclass
) )
408 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
413 // Register the panel window class.
414 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
415 wndclass
.lpszClassName
= wxPanelClassName
;
416 wndclass
.style
= styleNormal
;
418 if ( !RegisterClass(&wndclass
) )
420 wxLogLastError(wxT("RegisterClass(panel)"));
425 // Register the no redraw panel window class.
426 wndclass
.lpszClassName
= wxPanelClassNameNR
;
427 wndclass
.style
= styleNoRedraw
;
429 if ( !RegisterClass(&wndclass
) )
431 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
436 // Register the canvas and textsubwindow class name
437 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
438 wndclass
.lpszClassName
= wxCanvasClassName
;
440 if ( !RegisterClass(&wndclass
) )
442 wxLogLastError(wxT("RegisterClass(canvas)"));
447 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
448 wndclass
.style
= styleNoRedraw
;
449 if ( !RegisterClass(&wndclass
) )
451 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
459 // ---------------------------------------------------------------------------
460 // UnregisterWindowClasses
461 // ---------------------------------------------------------------------------
463 bool wxApp::UnregisterWindowClasses()
467 #ifndef __WXMICROWIN__
468 // frame window class.
469 if ( !UnregisterClass(wxFrameClassName
, wxhInstance
) )
471 wxLogLastError(wxT("UnregisterClass(frame)"));
477 if ( !UnregisterClass(wxFrameClassNameNoRedraw
, wxhInstance
) )
479 wxLogLastError(wxT("UnregisterClass(no redraw frame)"));
484 // MDI frame window class.
485 if ( !UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
487 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
492 // "no redraw" MDI frame
493 if ( !UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
495 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
500 // MDI child frame window class.
501 if ( !UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
503 wxLogLastError(wxT("UnregisterClass(MDI child)"));
508 // "no redraw" MDI child frame
509 if ( !UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
511 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
516 // panel window class.
517 if ( !UnregisterClass(wxPanelClassName
, wxhInstance
) )
519 wxLogLastError(wxT("UnregisterClass(panel)"));
524 // no redraw panel window class.
525 if ( !UnregisterClass(wxPanelClassNameNR
, wxhInstance
) )
527 wxLogLastError(wxT("UnregisterClass(no redraw panel)"));
532 // canvas and textsubwindow class name
533 if ( !UnregisterClass(wxCanvasClassName
, wxhInstance
) )
535 wxLogLastError(wxT("UnregisterClass(canvas)"));
540 if ( !UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
542 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
551 // ---------------------------------------------------------------------------
552 // Convert Windows to argc, argv style
553 // ---------------------------------------------------------------------------
555 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
557 // break the command line in words
559 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
561 // +1 here for the program name
562 argc
= args
.GetCount() + 1;
564 // and +1 here for the terminating NULL
565 argv
= new wxChar
*[argc
+ 1];
567 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
568 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
570 // also set the app name from argv[0]
572 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
576 // copy all the other arguments to wxApp::argv[]
577 for ( int i
= 1; i
< argc
; i
++ )
579 argv
[i
] = copystring(args
[i
- 1]);
582 // argv[] must be NULL-terminated
586 //// Cleans up any wxWindows internal structures left lying around
588 void wxApp::CleanUp()
593 // flush the logged messages if any and install a 'safer' log target: the
594 // default one (wxLogGui) can't be used after the resources are freed just
595 // below and the user suppliedo ne might be even more unsafe (using any
596 // wxWindows GUI function is unsafe starting from now)
597 wxLog::DontCreateOnDemand();
599 // this will flush the old messages if any
600 delete wxLog::SetActiveTarget(new wxLogStderr
);
603 // One last chance for pending objects to be cleaned up
604 wxTheApp
->DeletePendingObjects();
606 wxModule::CleanUpModules();
608 #if wxUSE_WX_RESOURCES
609 wxCleanUpResourceSystem();
611 // wxDefaultResourceTable->ClearTable();
614 wxDeleteStockObjects();
616 // Destroy all GDI lists, etc.
617 wxDeleteStockLists();
619 delete wxTheColourDatabase
;
620 wxTheColourDatabase
= NULL
;
622 wxBitmap::CleanUpHandlers();
627 //// WINDOWS-SPECIFIC CLEANUP
629 #ifndef __WXMICROWIN__
630 wxSetKeyboardHook(FALSE
);
637 if (wxSTD_FRAME_ICON
)
638 DestroyIcon(wxSTD_FRAME_ICON
);
639 if (wxSTD_MDICHILDFRAME_ICON
)
640 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
641 if (wxSTD_MDIPARENTFRAME_ICON
)
642 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
644 if (wxDEFAULT_FRAME_ICON
)
645 DestroyIcon(wxDEFAULT_FRAME_ICON
);
646 if (wxDEFAULT_MDICHILDFRAME_ICON
)
647 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
648 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
649 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
651 if ( wxDisableButtonBrush
)
652 ::DeleteObject( wxDisableButtonBrush
);
659 // for an EXE the classes are unregistered when it terminates but DLL may
660 // be loaded several times (load/unload/load) into the same process in
661 // which case the registration will fail after the first time if we don't
662 // unregister the classes now
663 UnregisterWindowClasses();
664 #endif // WXMAKINGDLL
667 Ctl3dUnregister(wxhInstance
);
670 delete wxWinHandleHash
;
672 // GL: I'm annoyed ... I don't know where to put this and I don't want to
673 // create a module for that as it's part of the core.
674 delete wxPendingEvents
;
677 delete wxPendingEventsLocker
;
678 // If we don't do the following, we get an apparent memory leak
680 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
681 #endif // wxUSE_VALIDATORS
682 #endif // wxUSE_THREADS
684 wxClassInfo::CleanUpClasses();
689 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
690 // At this point we want to check if there are any memory
691 // blocks that aren't part of the wxDebugContext itself,
692 // as a special case. Then when dumping we need to ignore
693 // wxDebugContext, too.
694 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
696 wxLogMessage(wxT("There were memory leaks."));
697 wxDebugContext::Dump();
698 wxDebugContext::PrintStatistics();
700 // wxDebugContext::SetStream(NULL, NULL);
704 // do it as the very last thing because everything else can log messages
705 delete wxLog::SetActiveTarget(NULL
);
709 //----------------------------------------------------------------------
710 // Entry point helpers, used by wxPython
711 //----------------------------------------------------------------------
713 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
715 return wxApp::Initialize();
718 int WXDLLEXPORT
wxEntryInitGui()
720 return wxTheApp
->OnInitGui();
723 void WXDLLEXPORT
wxEntryCleanup()
729 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
731 // temporarily disable this warning which would be generated in release builds
734 #pragma warning(disable: 4715) // not all control paths return a value
737 //----------------------------------------------------------------------
738 // Main wxWindows entry point
739 //----------------------------------------------------------------------
740 int wxEntry(WXHINSTANCE hInstance
,
741 WXHINSTANCE
WXUNUSED(hPrevInstance
),
746 // do check for memory leaks on program exit
747 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
748 // deallocated memory which may be used to simulate low-memory condition)
749 #ifndef __WXMICROWIN__
750 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
754 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
755 // This seems to be necessary since there are 'rogue'
756 // objects present at this point (perhaps global objects?)
757 // Setting a checkpoint will ignore them as far as the
758 // memory checking facility is concerned.
759 // Of course you may argue that memory allocated in globals should be
760 // checked, but this is a reasonable compromise.
761 wxDebugContext::SetCheckpoint();
765 // take everything into a try-except block to be able to call
766 // OnFatalException() if necessary
767 #if wxUSE_ON_FATAL_EXCEPTION
770 wxhInstance
= (HINSTANCE
) hInstance
;
772 if (!wxEntryStart(0,0))
775 // create the application object or ensure that one already exists
778 // The app may have declared a global application object, but we recommend
779 // the IMPLEMENT_APP macro is used instead, which sets an initializer
780 // function for delayed, dynamic app object construction.
781 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
782 wxT("No initializer - use IMPLEMENT_APP macro.") );
784 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
787 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
789 // save the WinMain() parameters
790 if (lpCmdLine
) // MicroWindows passes NULL
791 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
792 wxTheApp
->m_nCmdShow
= nCmdShow
;
794 // We really don't want timestamps by default, because it means
795 // we can't simply double-click on the error message and get to that
796 // line in the source. So VC++ at least, let's have a sensible default.
798 wxLog::SetTimestamp(NULL
);
803 // it is common to create a modal dialog in OnInit() (to ask/notify the
804 // user about something) but it wouldn't work if we don't change the
805 // "exit on delete last frame" flag here as when this dialog is
806 // deleted, the app would terminate (it was the last top level window
807 // as the main frame wasn't created yet!), so disable this behaviour
809 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
810 wxTheApp
->SetExitOnFrameDelete(FALSE
);
813 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
815 // restore the old flag value
816 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
823 retValue
= wxTheApp
->OnRun();
827 // we want to initialize, but not run or exit immediately.
831 //else: app initialization failed, so we skipped OnRun()
833 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
836 // Forcibly delete the window.
837 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
838 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
840 topWindow
->Close(TRUE
);
841 wxTheApp
->DeletePendingObjects();
846 wxTheApp
->SetTopWindow(NULL
);
856 #if wxUSE_ON_FATAL_EXCEPTION
858 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
859 : EXCEPTION_CONTINUE_SEARCH
) {
862 // give the user a chance to do something special about this
863 wxTheApp
->OnFatalException();
866 ::ExitProcess(3); // the same exit code as abort()
870 #endif // wxUSE_ON_FATAL_EXCEPTION
873 // restore warning state
875 #pragma warning(default: 4715) // not all control paths return a value
880 //----------------------------------------------------------------------
881 // Entry point for wxWindows + the App in a DLL
882 //----------------------------------------------------------------------
884 int wxEntry(WXHINSTANCE hInstance
)
886 wxhInstance
= (HINSTANCE
) hInstance
;
889 // The app may have declared a global application object, but we recommend
890 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
891 // for delayed, dynamic app object construction.
894 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
895 "No initializer - use IMPLEMENT_APP macro." );
897 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
900 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
903 wxTheApp
->argv
= NULL
;
909 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
910 if ( topWindow
&& topWindow
->GetHWND())
912 topWindow
->Show(TRUE
);
919 //// Static member initialization
921 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
927 m_printMode
= wxPRINT_WINDOWS
;
933 // Delete command-line args
935 for (i
= 0; i
< argc
; i
++)
942 bool wxApp::Initialized()
949 #else // Assume initialized if DLL (no way of telling)
955 * Get and process a message, returning FALSE if WM_QUIT
956 * received (and also set the flag telling the app to exit the main loop)
959 bool wxApp::DoMessage()
961 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
971 // should never happen, but let's test for it nevertheless
972 wxLogLastError(wxT("GetMessage"));
977 wxASSERT_MSG( wxThread::IsMain(),
978 wxT("only the main thread can process Windows messages") );
980 static bool s_hadGuiLock
= TRUE
;
981 static wxMsgArray s_aSavedMessages
;
983 // if a secondary thread owns is doing GUI calls, save all messages for
984 // later processing - we can't process them right now because it will
985 // lead to recursive library calls (and we're not reentrant)
986 if ( !wxGuiOwnedByMainThread() )
988 s_hadGuiLock
= FALSE
;
990 // leave out WM_COMMAND messages: too dangerous, sometimes
991 // the message will be processed twice
992 if ( !wxIsWaitingForThread() ||
993 s_currentMsg
.message
!= WM_COMMAND
)
995 s_aSavedMessages
.Add(s_currentMsg
);
1002 // have we just regained the GUI lock? if so, post all of the saved
1005 // FIXME of course, it's not _exactly_ the same as processing the
1006 // messages normally - expect some things to break...
1007 if ( !s_hadGuiLock
)
1009 s_hadGuiLock
= TRUE
;
1011 size_t count
= s_aSavedMessages
.Count();
1012 for ( size_t n
= 0; n
< count
; n
++ )
1014 MSG
& msg
= s_aSavedMessages
[n
];
1016 if ( !ProcessMessage((WXMSG
*)&msg
) )
1018 ::TranslateMessage(&msg
);
1019 ::DispatchMessage(&msg
);
1023 s_aSavedMessages
.Empty();
1026 #endif // wxUSE_THREADS
1028 // Process the message
1029 DoMessage((WXMSG
*)&s_currentMsg
);
1035 void wxApp::DoMessage(WXMSG
*pMsg
)
1037 if ( !ProcessMessage(pMsg
) )
1039 ::TranslateMessage((MSG
*)pMsg
);
1040 ::DispatchMessage((MSG
*)pMsg
);
1045 * Keep trying to process messages until WM_QUIT
1048 * If there are messages to be processed, they will all be
1049 * processed and OnIdle will not be called.
1050 * When there are no more messages, OnIdle is called.
1051 * If OnIdle requests more time,
1052 * it will be repeatedly called so long as there are no pending messages.
1053 * A 'feature' of this is that once OnIdle has decided that no more processing
1054 * is required, then it won't get processing time until further messages
1055 * are processed (it'll sit in DoMessage).
1058 int wxApp::MainLoop()
1062 while ( m_keepGoing
)
1065 wxMutexGuiLeaveOrEnter();
1066 #endif // wxUSE_THREADS
1068 while ( !Pending() && ProcessIdle() )
1071 // a message came or no more idle processing to do
1075 return s_currentMsg
.wParam
;
1078 // Returns TRUE if more time is needed.
1079 bool wxApp::ProcessIdle()
1082 event
.SetEventObject(this);
1083 ProcessEvent(event
);
1085 return event
.MoreRequested();
1088 void wxApp::ExitMainLoop()
1090 // VZ: why not ::PostQuitMessage()?
1091 m_keepGoing
= FALSE
;
1094 bool wxApp::Pending()
1096 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1099 void wxApp::Dispatch()
1105 * Give all windows a chance to preprocess
1106 * the message. Some may have accelerator tables, or have
1107 * MDI complications.
1110 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1112 MSG
*msg
= (MSG
*)wxmsg
;
1113 HWND hwnd
= msg
->hwnd
;
1114 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1116 // this may happen if the event occured in a standard modeless dialog (the
1117 // only example of which I know of is the find/replace dialog) - then call
1118 // IsDialogMessage() to make TAB navigation in it work
1121 // we need to find the dialog containing this control as
1122 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1123 // them) if we call it for the control itself
1124 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1126 hwnd
= ::GetParent(hwnd
);
1129 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1133 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1134 // popup the tooltip bubbles
1135 if ( (msg
->message
== WM_MOUSEMOVE
) )
1137 wxToolTip
*tt
= wndThis
->GetToolTip();
1140 tt
->RelayEvent(wxmsg
);
1143 #endif // wxUSE_TOOLTIPS
1145 // allow the window to prevent certain messages from being
1146 // translated/processed (this is currently used by wxTextCtrl to always
1147 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1148 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1153 // try translations first: the accelerators override everything
1156 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1158 if ( wnd
->MSWTranslateMessage(wxmsg
))
1161 // stop at first top level window, i.e. don't try to process the key
1162 // strokes originating in a dialog using the accelerators of the parent
1163 // frame - this doesn't make much sense
1164 if ( wnd
->IsTopLevel() )
1168 // now try the other hooks (kbd navigation is handled here): we start from
1169 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1171 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1173 if ( wnd
->MSWProcessMessage(wxmsg
) )
1177 // no special preprocessing for this message, dispatch it normally
1181 void wxApp::OnIdle(wxIdleEvent
& event
)
1183 static bool s_inOnIdle
= FALSE
;
1185 // Avoid recursion (via ProcessEvent default case)
1191 // If there are pending events, we must process them: pending events
1192 // are either events to the threads other than main or events posted
1193 // with wxPostEvent() functions
1194 // GRG: I have moved this here so that all pending events are processed
1195 // before starting to delete any objects. This behaves better (in
1196 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1197 // behaviour. Changed Feb/2000 before 2.1.14
1198 ProcessPendingEvents();
1200 // 'Garbage' collection of windows deleted with Close().
1201 DeletePendingObjects();
1204 // flush the logged messages if any
1205 wxLog::FlushActive();
1208 #if wxUSE_DC_CACHEING
1209 // automated DC cache management: clear the cached DCs and bitmap
1210 // if it's likely that the app has finished with them, that is, we
1211 // get an idle event and we're not dragging anything.
1212 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1214 #endif // wxUSE_DC_CACHEING
1216 // Send OnIdle events to all windows
1217 if ( SendIdleEvents() )
1219 // SendIdleEvents() returns TRUE if at least one window requested more
1221 event
.RequestMore(TRUE
);
1227 // Send idle event to all top-level windows
1228 bool wxApp::SendIdleEvents()
1230 bool needMore
= FALSE
;
1232 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1235 wxWindow
* win
= node
->GetData();
1236 if (SendIdleEvents(win
))
1238 node
= node
->GetNext();
1244 // Send idle event to window and all subwindows
1245 bool wxApp::SendIdleEvents(wxWindow
* win
)
1247 bool needMore
= FALSE
;
1250 event
.SetEventObject(win
);
1251 win
->GetEventHandler()->ProcessEvent(event
);
1253 if (event
.MoreRequested())
1256 wxNode
* node
= win
->GetChildren().First();
1259 wxWindow
* win
= (wxWindow
*) node
->Data();
1260 if (SendIdleEvents(win
))
1263 node
= node
->Next();
1268 void wxApp::DeletePendingObjects()
1270 wxNode
*node
= wxPendingDelete
.First();
1273 wxObject
*obj
= (wxObject
*)node
->Data();
1277 if (wxPendingDelete
.Member(obj
))
1280 // Deleting one object may have deleted other pending
1281 // objects, so start from beginning of list again.
1282 node
= wxPendingDelete
.First();
1286 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1289 GetTopWindow()->Close(TRUE
);
1292 // Default behaviour: close the application with prompts. The
1293 // user can veto the close, and therefore the end session.
1294 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1298 if (!GetTopWindow()->Close(!event
.CanVeto()))
1304 int wxApp::GetComCtl32Version()
1306 #ifdef __WXMICROWIN__
1310 static int s_verComCtl32
= -1;
1312 wxCRIT_SECT_DECLARE(csComCtl32
);
1313 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1315 if ( s_verComCtl32
== -1 )
1317 // initally assume no comctl32.dll at all
1321 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1323 // if so, then we can check for the version
1324 if ( hModuleComCtl32
)
1326 // try to use DllGetVersion() if available in _headers_
1327 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1328 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1329 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1330 if ( pfnDllGetVersion
)
1333 dvi
.cbSize
= sizeof(dvi
);
1335 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1338 wxLogApiError(_T("DllGetVersion"), hr
);
1342 // this is incompatible with _WIN32_IE values, but
1343 // compatible with the other values returned by
1344 // GetComCtl32Version()
1345 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1350 // DllGetVersion() unavailable either during compile or
1351 // run-time, try to guess the version otherwise
1352 if ( !s_verComCtl32
)
1354 // InitCommonControlsEx is unique to 4.70 and later
1355 FARPROC theProc
= ::GetProcAddress
1358 "InitCommonControlsEx"
1363 // not found, must be 4.00
1364 s_verComCtl32
= 400;
1368 // many symbols appeared in comctl32 4.71, could use
1369 // any of them except may be DllInstall
1370 theProc
= ::GetProcAddress
1377 // not found, must be 4.70
1378 s_verComCtl32
= 470;
1382 // found, must be 4.71
1383 s_verComCtl32
= 471;
1390 return s_verComCtl32
;
1396 wxLogError(_("Fatal error: exiting"));
1402 // Yield to incoming messages
1404 bool wxApp::Yield(bool onlyIfNeeded
)
1407 static bool s_inYield
= FALSE
;
1409 // disable log flushing from here because a call to wxYield() shouldn't
1410 // normally result in message boxes popping up &c
1415 if ( !onlyIfNeeded
)
1417 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1425 // we don't want to process WM_QUIT from here - it should be processed in
1426 // the main event loop in order to stop it
1428 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1429 msg
.message
!= WM_QUIT
)
1432 wxMutexGuiLeaveOrEnter();
1433 #endif // wxUSE_THREADS
1435 if ( !wxTheApp
->DoMessage() )
1439 // if there are pending events, we must process them.
1440 ProcessPendingEvents();
1442 // let the logs be flashed again
1450 bool wxHandleFatalExceptions(bool doit
)
1452 #if wxUSE_ON_FATAL_EXCEPTION
1453 // assume this can only be called from the main thread
1454 gs_handleExceptions
= doit
;
1458 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1465 //-----------------------------------------------------------------------------
1467 //-----------------------------------------------------------------------------
1471 // Send the top window a dummy message so idle handler processing will
1472 // start up again. Doing it this way ensures that the idle handler
1473 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1474 // the same for the main app thread only)
1475 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1478 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1480 // should never happen
1481 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1486 //-----------------------------------------------------------------------------
1489 wxApp::GetStdIcon(int which
) const
1493 case wxICON_INFORMATION
:
1494 return wxIcon("wxICON_INFO");
1496 case wxICON_QUESTION
:
1497 return wxIcon("wxICON_QUESTION");
1499 case wxICON_EXCLAMATION
:
1500 return wxIcon("wxICON_WARNING");
1503 wxFAIL_MSG(wxT("requested non existent standard icon"));
1504 // still fall through
1507 return wxIcon("wxICON_ERROR");
1511 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1512 // if in a separate file. So include it here to ensure it's linked.
1513 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))