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 w/o MSLU emulation layer - if so, abort right now
197 // as it has no chance to work
198 #if wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
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/XP.\nProgram aborted."),
208 _T("wxWindows Fatal Error"),
214 #endif // wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
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))
256 // we need to initialize OLE library
257 if ( FAILED(::OleInitialize(NULL
)) )
258 wxLogError(_("Cannot initialize OLE"));
264 if (!Ctl3dRegister(wxhInstance
))
265 wxLogError(wxT("Cannot register CTL3D"));
267 Ctl3dAutoSubclass(wxhInstance
);
268 #endif // wxUSE_CTL3D
270 // VZ: these icons are not in wx.rc anyhow (but should they?)!
272 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
273 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
274 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
276 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
277 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
278 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
281 RegisterWindowClasses();
283 #ifndef __WXMICROWIN__
284 // Create the brush for disabling bitmap buttons
287 lb
.lbStyle
= BS_PATTERN
;
289 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
292 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
293 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
295 //else: wxWindows resources are probably not linked in
302 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
304 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
305 // PLEASE DO NOT ALTER THIS.
306 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
307 extern char wxDummyChar
;
308 if (wxDummyChar
) wxDummyChar
++;
311 #ifndef __WXMICROWIN__
312 wxSetKeyboardHook(TRUE
);
315 wxModule::RegisterModules();
316 if (!wxModule::InitializeModules())
321 // ---------------------------------------------------------------------------
322 // RegisterWindowClasses
323 // ---------------------------------------------------------------------------
325 // TODO we should only register classes really used by the app. For this it
326 // would be enough to just delay the class registration until an attempt
327 // to create a window of this class is made.
328 bool wxApp::RegisterWindowClasses()
332 // for each class we register one with CS_(V|H)REDRAW style and one
333 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
334 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
335 static const long styleNoRedraw
= CS_DBLCLKS
;
337 // the fields which are common to all classes
338 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
339 wndclass
.cbClsExtra
= 0;
340 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
341 wndclass
.hInstance
= wxhInstance
;
342 wndclass
.hIcon
= (HICON
) NULL
;
343 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
344 wndclass
.lpszMenuName
= NULL
;
346 // Register the frame window class.
347 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
348 wndclass
.lpszClassName
= wxFrameClassName
;
349 wndclass
.style
= styleNormal
;
351 if ( !RegisterClass(&wndclass
) )
353 wxLogLastError(wxT("RegisterClass(frame)"));
359 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
360 wndclass
.style
= styleNoRedraw
;
362 if ( !RegisterClass(&wndclass
) )
364 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
369 // Register the MDI frame window class.
370 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
371 wndclass
.lpszClassName
= wxMDIFrameClassName
;
372 wndclass
.style
= styleNormal
;
374 if ( !RegisterClass(&wndclass
) )
376 wxLogLastError(wxT("RegisterClass(MDI parent)"));
381 // "no redraw" MDI frame
382 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
383 wndclass
.style
= styleNoRedraw
;
385 if ( !RegisterClass(&wndclass
) )
387 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
392 // Register the MDI child frame window class.
393 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
394 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
395 wndclass
.style
= styleNormal
;
397 if ( !RegisterClass(&wndclass
) )
399 wxLogLastError(wxT("RegisterClass(MDI child)"));
404 // "no redraw" MDI child frame
405 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
406 wndclass
.style
= styleNoRedraw
;
408 if ( !RegisterClass(&wndclass
) )
410 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
415 // Register the panel window class.
416 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
417 wndclass
.lpszClassName
= wxPanelClassName
;
418 wndclass
.style
= styleNormal
;
420 if ( !RegisterClass(&wndclass
) )
422 wxLogLastError(wxT("RegisterClass(panel)"));
427 // Register the no redraw panel window class.
428 wndclass
.lpszClassName
= wxPanelClassNameNR
;
429 wndclass
.style
= styleNoRedraw
;
431 if ( !RegisterClass(&wndclass
) )
433 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
438 // Register the canvas and textsubwindow class name
439 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
440 wndclass
.lpszClassName
= wxCanvasClassName
;
442 if ( !RegisterClass(&wndclass
) )
444 wxLogLastError(wxT("RegisterClass(canvas)"));
449 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
450 wndclass
.style
= styleNoRedraw
;
451 if ( !RegisterClass(&wndclass
) )
453 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
461 // ---------------------------------------------------------------------------
462 // UnregisterWindowClasses
463 // ---------------------------------------------------------------------------
465 bool wxApp::UnregisterWindowClasses()
469 #ifndef __WXMICROWIN__
470 // frame window class.
471 if ( !UnregisterClass(wxFrameClassName
, wxhInstance
) )
473 wxLogLastError(wxT("UnregisterClass(frame)"));
479 if ( !UnregisterClass(wxFrameClassNameNoRedraw
, wxhInstance
) )
481 wxLogLastError(wxT("UnregisterClass(no redraw frame)"));
486 // MDI frame window class.
487 if ( !UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
489 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
494 // "no redraw" MDI frame
495 if ( !UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
497 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
502 // MDI child frame window class.
503 if ( !UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
505 wxLogLastError(wxT("UnregisterClass(MDI child)"));
510 // "no redraw" MDI child frame
511 if ( !UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
513 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
518 // panel window class.
519 if ( !UnregisterClass(wxPanelClassName
, wxhInstance
) )
521 wxLogLastError(wxT("UnregisterClass(panel)"));
526 // no redraw panel window class.
527 if ( !UnregisterClass(wxPanelClassNameNR
, wxhInstance
) )
529 wxLogLastError(wxT("UnregisterClass(no redraw panel)"));
534 // canvas and textsubwindow class name
535 if ( !UnregisterClass(wxCanvasClassName
, wxhInstance
) )
537 wxLogLastError(wxT("UnregisterClass(canvas)"));
542 if ( !UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
544 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
553 // ---------------------------------------------------------------------------
554 // Convert Windows to argc, argv style
555 // ---------------------------------------------------------------------------
557 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
559 // break the command line in words
561 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
563 // +1 here for the program name
564 argc
= args
.GetCount() + 1;
566 // and +1 here for the terminating NULL
567 argv
= new wxChar
*[argc
+ 1];
569 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
570 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
572 // also set the app name from argv[0]
574 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
578 // copy all the other arguments to wxApp::argv[]
579 for ( int i
= 1; i
< argc
; i
++ )
581 argv
[i
] = copystring(args
[i
- 1]);
584 // argv[] must be NULL-terminated
588 //// Cleans up any wxWindows internal structures left lying around
590 void wxApp::CleanUp()
595 // flush the logged messages if any and install a 'safer' log target: the
596 // default one (wxLogGui) can't be used after the resources are freed just
597 // below and the user suppliedo ne might be even more unsafe (using any
598 // wxWindows GUI function is unsafe starting from now)
599 wxLog::DontCreateOnDemand();
601 // this will flush the old messages if any
602 delete wxLog::SetActiveTarget(new wxLogStderr
);
605 // One last chance for pending objects to be cleaned up
606 wxTheApp
->DeletePendingObjects();
608 wxModule::CleanUpModules();
610 #if wxUSE_WX_RESOURCES
611 wxCleanUpResourceSystem();
613 // wxDefaultResourceTable->ClearTable();
616 wxDeleteStockObjects();
618 // Destroy all GDI lists, etc.
619 wxDeleteStockLists();
621 delete wxTheColourDatabase
;
622 wxTheColourDatabase
= NULL
;
624 wxBitmap::CleanUpHandlers();
629 //// WINDOWS-SPECIFIC CLEANUP
631 #ifndef __WXMICROWIN__
632 wxSetKeyboardHook(FALSE
);
639 if (wxSTD_FRAME_ICON
)
640 DestroyIcon(wxSTD_FRAME_ICON
);
641 if (wxSTD_MDICHILDFRAME_ICON
)
642 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
643 if (wxSTD_MDIPARENTFRAME_ICON
)
644 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
646 if (wxDEFAULT_FRAME_ICON
)
647 DestroyIcon(wxDEFAULT_FRAME_ICON
);
648 if (wxDEFAULT_MDICHILDFRAME_ICON
)
649 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
650 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
651 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
653 if ( wxDisableButtonBrush
)
654 ::DeleteObject( wxDisableButtonBrush
);
661 // for an EXE the classes are unregistered when it terminates but DLL may
662 // be loaded several times (load/unload/load) into the same process in
663 // which case the registration will fail after the first time if we don't
664 // unregister the classes now
665 UnregisterWindowClasses();
666 #endif // WXMAKINGDLL
669 Ctl3dUnregister(wxhInstance
);
672 delete wxWinHandleHash
;
674 // GL: I'm annoyed ... I don't know where to put this and I don't want to
675 // create a module for that as it's part of the core.
676 delete wxPendingEvents
;
679 delete wxPendingEventsLocker
;
680 // If we don't do the following, we get an apparent memory leak
682 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
683 #endif // wxUSE_VALIDATORS
684 #endif // wxUSE_THREADS
686 wxClassInfo::CleanUpClasses();
691 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
692 // At this point we want to check if there are any memory
693 // blocks that aren't part of the wxDebugContext itself,
694 // as a special case. Then when dumping we need to ignore
695 // wxDebugContext, too.
696 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
698 wxLogMessage(wxT("There were memory leaks."));
699 wxDebugContext::Dump();
700 wxDebugContext::PrintStatistics();
702 // wxDebugContext::SetStream(NULL, NULL);
706 // do it as the very last thing because everything else can log messages
707 delete wxLog::SetActiveTarget(NULL
);
711 //----------------------------------------------------------------------
712 // Entry point helpers, used by wxPython
713 //----------------------------------------------------------------------
715 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
717 return wxApp::Initialize();
720 int WXDLLEXPORT
wxEntryInitGui()
722 return wxTheApp
->OnInitGui();
725 void WXDLLEXPORT
wxEntryCleanup()
731 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
733 // temporarily disable this warning which would be generated in release builds
736 #pragma warning(disable: 4715) // not all control paths return a value
739 //----------------------------------------------------------------------
740 // Main wxWindows entry point
741 //----------------------------------------------------------------------
742 int wxEntry(WXHINSTANCE hInstance
,
743 WXHINSTANCE
WXUNUSED(hPrevInstance
),
748 // do check for memory leaks on program exit
749 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
750 // deallocated memory which may be used to simulate low-memory condition)
751 #ifndef __WXMICROWIN__
752 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
756 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
757 // This seems to be necessary since there are 'rogue'
758 // objects present at this point (perhaps global objects?)
759 // Setting a checkpoint will ignore them as far as the
760 // memory checking facility is concerned.
761 // Of course you may argue that memory allocated in globals should be
762 // checked, but this is a reasonable compromise.
763 wxDebugContext::SetCheckpoint();
767 // take everything into a try-except block to be able to call
768 // OnFatalException() if necessary
769 #if wxUSE_ON_FATAL_EXCEPTION
772 wxhInstance
= (HINSTANCE
) hInstance
;
774 if (!wxEntryStart(0,0))
777 // create the application object or ensure that one already exists
780 // The app may have declared a global application object, but we recommend
781 // the IMPLEMENT_APP macro is used instead, which sets an initializer
782 // function for delayed, dynamic app object construction.
783 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
784 wxT("No initializer - use IMPLEMENT_APP macro.") );
786 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
789 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
791 // save the WinMain() parameters
792 if (lpCmdLine
) // MicroWindows passes NULL
793 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
794 wxTheApp
->m_nCmdShow
= nCmdShow
;
796 // We really don't want timestamps by default, because it means
797 // we can't simply double-click on the error message and get to that
798 // line in the source. So VC++ at least, let's have a sensible default.
800 wxLog::SetTimestamp(NULL
);
805 // it is common to create a modal dialog in OnInit() (to ask/notify the
806 // user about something) but it wouldn't work if we don't change the
807 // "exit on delete last frame" flag here as when this dialog is
808 // deleted, the app would terminate (it was the last top level window
809 // as the main frame wasn't created yet!), so disable this behaviour
811 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
812 wxTheApp
->SetExitOnFrameDelete(FALSE
);
815 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
817 // restore the old flag value
818 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
825 retValue
= wxTheApp
->OnRun();
829 // we want to initialize, but not run or exit immediately.
833 //else: app initialization failed, so we skipped OnRun()
835 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
838 // Forcibly delete the window.
839 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
840 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
842 topWindow
->Close(TRUE
);
843 wxTheApp
->DeletePendingObjects();
848 wxTheApp
->SetTopWindow(NULL
);
858 #if wxUSE_ON_FATAL_EXCEPTION
860 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
861 : EXCEPTION_CONTINUE_SEARCH
) {
864 // give the user a chance to do something special about this
865 wxTheApp
->OnFatalException();
868 ::ExitProcess(3); // the same exit code as abort()
872 #endif // wxUSE_ON_FATAL_EXCEPTION
875 // restore warning state
877 #pragma warning(default: 4715) // not all control paths return a value
882 //----------------------------------------------------------------------
883 // Entry point for wxWindows + the App in a DLL
884 //----------------------------------------------------------------------
886 int wxEntry(WXHINSTANCE hInstance
)
888 wxhInstance
= (HINSTANCE
) hInstance
;
891 // The app may have declared a global application object, but we recommend
892 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
893 // for delayed, dynamic app object construction.
896 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
897 "No initializer - use IMPLEMENT_APP macro." );
899 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
902 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
905 wxTheApp
->argv
= NULL
;
911 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
912 if ( topWindow
&& topWindow
->GetHWND())
914 topWindow
->Show(TRUE
);
921 //// Static member initialization
923 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
929 m_printMode
= wxPRINT_WINDOWS
;
935 // Delete command-line args
937 for (i
= 0; i
< argc
; i
++)
944 bool wxApp::Initialized()
951 #else // Assume initialized if DLL (no way of telling)
957 * Get and process a message, returning FALSE if WM_QUIT
958 * received (and also set the flag telling the app to exit the main loop)
961 bool wxApp::DoMessage()
963 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
973 // should never happen, but let's test for it nevertheless
974 wxLogLastError(wxT("GetMessage"));
979 wxASSERT_MSG( wxThread::IsMain(),
980 wxT("only the main thread can process Windows messages") );
982 static bool s_hadGuiLock
= TRUE
;
983 static wxMsgArray s_aSavedMessages
;
985 // if a secondary thread owns is doing GUI calls, save all messages for
986 // later processing - we can't process them right now because it will
987 // lead to recursive library calls (and we're not reentrant)
988 if ( !wxGuiOwnedByMainThread() )
990 s_hadGuiLock
= FALSE
;
992 // leave out WM_COMMAND messages: too dangerous, sometimes
993 // the message will be processed twice
994 if ( !wxIsWaitingForThread() ||
995 s_currentMsg
.message
!= WM_COMMAND
)
997 s_aSavedMessages
.Add(s_currentMsg
);
1004 // have we just regained the GUI lock? if so, post all of the saved
1007 // FIXME of course, it's not _exactly_ the same as processing the
1008 // messages normally - expect some things to break...
1009 if ( !s_hadGuiLock
)
1011 s_hadGuiLock
= TRUE
;
1013 size_t count
= s_aSavedMessages
.Count();
1014 for ( size_t n
= 0; n
< count
; n
++ )
1016 MSG
& msg
= s_aSavedMessages
[n
];
1018 if ( !ProcessMessage((WXMSG
*)&msg
) )
1020 ::TranslateMessage(&msg
);
1021 ::DispatchMessage(&msg
);
1025 s_aSavedMessages
.Empty();
1028 #endif // wxUSE_THREADS
1030 // Process the message
1031 DoMessage((WXMSG
*)&s_currentMsg
);
1037 void wxApp::DoMessage(WXMSG
*pMsg
)
1039 if ( !ProcessMessage(pMsg
) )
1041 ::TranslateMessage((MSG
*)pMsg
);
1042 ::DispatchMessage((MSG
*)pMsg
);
1047 * Keep trying to process messages until WM_QUIT
1050 * If there are messages to be processed, they will all be
1051 * processed and OnIdle will not be called.
1052 * When there are no more messages, OnIdle is called.
1053 * If OnIdle requests more time,
1054 * it will be repeatedly called so long as there are no pending messages.
1055 * A 'feature' of this is that once OnIdle has decided that no more processing
1056 * is required, then it won't get processing time until further messages
1057 * are processed (it'll sit in DoMessage).
1060 int wxApp::MainLoop()
1064 while ( m_keepGoing
)
1067 wxMutexGuiLeaveOrEnter();
1068 #endif // wxUSE_THREADS
1070 while ( !Pending() && ProcessIdle() )
1073 // a message came or no more idle processing to do
1077 return s_currentMsg
.wParam
;
1080 // Returns TRUE if more time is needed.
1081 bool wxApp::ProcessIdle()
1084 event
.SetEventObject(this);
1085 ProcessEvent(event
);
1087 return event
.MoreRequested();
1090 void wxApp::ExitMainLoop()
1092 // VZ: why not ::PostQuitMessage()?
1093 m_keepGoing
= FALSE
;
1096 bool wxApp::Pending()
1098 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1101 void wxApp::Dispatch()
1107 * Give all windows a chance to preprocess
1108 * the message. Some may have accelerator tables, or have
1109 * MDI complications.
1112 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1114 MSG
*msg
= (MSG
*)wxmsg
;
1115 HWND hwnd
= msg
->hwnd
;
1116 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1118 // this may happen if the event occured in a standard modeless dialog (the
1119 // only example of which I know of is the find/replace dialog) - then call
1120 // IsDialogMessage() to make TAB navigation in it work
1123 // we need to find the dialog containing this control as
1124 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1125 // them) if we call it for the control itself
1126 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1128 hwnd
= ::GetParent(hwnd
);
1131 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1135 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1136 // popup the tooltip bubbles
1137 if ( (msg
->message
== WM_MOUSEMOVE
) )
1139 wxToolTip
*tt
= wndThis
->GetToolTip();
1142 tt
->RelayEvent(wxmsg
);
1145 #endif // wxUSE_TOOLTIPS
1147 // allow the window to prevent certain messages from being
1148 // translated/processed (this is currently used by wxTextCtrl to always
1149 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1150 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1155 // try translations first: the accelerators override everything
1158 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1160 if ( wnd
->MSWTranslateMessage(wxmsg
))
1163 // stop at first top level window, i.e. don't try to process the key
1164 // strokes originating in a dialog using the accelerators of the parent
1165 // frame - this doesn't make much sense
1166 if ( wnd
->IsTopLevel() )
1170 // now try the other hooks (kbd navigation is handled here): we start from
1171 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1173 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1175 if ( wnd
->MSWProcessMessage(wxmsg
) )
1179 // no special preprocessing for this message, dispatch it normally
1183 void wxApp::OnIdle(wxIdleEvent
& event
)
1185 static bool s_inOnIdle
= FALSE
;
1187 // Avoid recursion (via ProcessEvent default case)
1193 // If there are pending events, we must process them: pending events
1194 // are either events to the threads other than main or events posted
1195 // with wxPostEvent() functions
1196 // GRG: I have moved this here so that all pending events are processed
1197 // before starting to delete any objects. This behaves better (in
1198 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1199 // behaviour. Changed Feb/2000 before 2.1.14
1200 ProcessPendingEvents();
1202 // 'Garbage' collection of windows deleted with Close().
1203 DeletePendingObjects();
1206 // flush the logged messages if any
1207 wxLog::FlushActive();
1210 #if wxUSE_DC_CACHEING
1211 // automated DC cache management: clear the cached DCs and bitmap
1212 // if it's likely that the app has finished with them, that is, we
1213 // get an idle event and we're not dragging anything.
1214 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1216 #endif // wxUSE_DC_CACHEING
1218 // Send OnIdle events to all windows
1219 if ( SendIdleEvents() )
1221 // SendIdleEvents() returns TRUE if at least one window requested more
1223 event
.RequestMore(TRUE
);
1229 // Send idle event to all top-level windows
1230 bool wxApp::SendIdleEvents()
1232 bool needMore
= FALSE
;
1234 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1237 wxWindow
* win
= node
->GetData();
1238 if (SendIdleEvents(win
))
1240 node
= node
->GetNext();
1246 // Send idle event to window and all subwindows
1247 bool wxApp::SendIdleEvents(wxWindow
* win
)
1249 bool needMore
= FALSE
;
1252 event
.SetEventObject(win
);
1253 win
->GetEventHandler()->ProcessEvent(event
);
1255 if (event
.MoreRequested())
1258 wxNode
* node
= win
->GetChildren().First();
1261 wxWindow
* win
= (wxWindow
*) node
->Data();
1262 if (SendIdleEvents(win
))
1265 node
= node
->Next();
1270 void wxApp::DeletePendingObjects()
1272 wxNode
*node
= wxPendingDelete
.First();
1275 wxObject
*obj
= (wxObject
*)node
->Data();
1279 if (wxPendingDelete
.Member(obj
))
1282 // Deleting one object may have deleted other pending
1283 // objects, so start from beginning of list again.
1284 node
= wxPendingDelete
.First();
1288 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1291 GetTopWindow()->Close(TRUE
);
1294 // Default behaviour: close the application with prompts. The
1295 // user can veto the close, and therefore the end session.
1296 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1300 if (!GetTopWindow()->Close(!event
.CanVeto()))
1306 int wxApp::GetComCtl32Version()
1308 #ifdef __WXMICROWIN__
1312 static int s_verComCtl32
= -1;
1314 wxCRIT_SECT_DECLARE(csComCtl32
);
1315 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1317 if ( s_verComCtl32
== -1 )
1319 // initally assume no comctl32.dll at all
1323 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1325 // if so, then we can check for the version
1326 if ( hModuleComCtl32
)
1328 // try to use DllGetVersion() if available in _headers_
1329 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1330 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1331 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1332 if ( pfnDllGetVersion
)
1335 dvi
.cbSize
= sizeof(dvi
);
1337 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1340 wxLogApiError(_T("DllGetVersion"), hr
);
1344 // this is incompatible with _WIN32_IE values, but
1345 // compatible with the other values returned by
1346 // GetComCtl32Version()
1347 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1352 // DllGetVersion() unavailable either during compile or
1353 // run-time, try to guess the version otherwise
1354 if ( !s_verComCtl32
)
1356 // InitCommonControlsEx is unique to 4.70 and later
1357 FARPROC theProc
= ::GetProcAddress
1360 "InitCommonControlsEx"
1365 // not found, must be 4.00
1366 s_verComCtl32
= 400;
1370 // many symbols appeared in comctl32 4.71, could use
1371 // any of them except may be DllInstall
1372 theProc
= ::GetProcAddress
1379 // not found, must be 4.70
1380 s_verComCtl32
= 470;
1384 // found, must be 4.71
1385 s_verComCtl32
= 471;
1392 return s_verComCtl32
;
1398 wxLogError(_("Fatal error: exiting"));
1404 // Yield to incoming messages
1406 bool wxApp::Yield(bool onlyIfNeeded
)
1409 static bool s_inYield
= FALSE
;
1411 // disable log flushing from here because a call to wxYield() shouldn't
1412 // normally result in message boxes popping up &c
1417 if ( !onlyIfNeeded
)
1419 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1427 // we don't want to process WM_QUIT from here - it should be processed in
1428 // the main event loop in order to stop it
1430 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1431 msg
.message
!= WM_QUIT
)
1434 wxMutexGuiLeaveOrEnter();
1435 #endif // wxUSE_THREADS
1437 if ( !wxTheApp
->DoMessage() )
1441 // if there are pending events, we must process them.
1442 ProcessPendingEvents();
1444 // let the logs be flashed again
1452 bool wxHandleFatalExceptions(bool doit
)
1454 #if wxUSE_ON_FATAL_EXCEPTION
1455 // assume this can only be called from the main thread
1456 gs_handleExceptions
= doit
;
1460 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1467 //-----------------------------------------------------------------------------
1469 //-----------------------------------------------------------------------------
1473 // Send the top window a dummy message so idle handler processing will
1474 // start up again. Doing it this way ensures that the idle handler
1475 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1476 // the same for the main app thread only)
1477 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1480 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1482 // should never happen
1483 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1488 //-----------------------------------------------------------------------------
1491 wxApp::GetStdIcon(int which
) const
1495 case wxICON_INFORMATION
:
1496 return wxIcon("wxICON_INFO");
1498 case wxICON_QUESTION
:
1499 return wxIcon("wxICON_QUESTION");
1501 case wxICON_EXCLAMATION
:
1502 return wxIcon("wxICON_WARNING");
1505 wxFAIL_MSG(wxT("requested non existent standard icon"));
1506 // still fall through
1509 return wxIcon("wxICON_ERROR");
1513 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1514 // if in a separate file. So include it here to ensure it's linked.
1515 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))