1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
21 #pragma implementation "app.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
27 #if defined(__BORLANDC__)
35 #include "wx/gdicmn.h"
38 #include "wx/cursor.h"
40 #include "wx/palette.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
51 #include "wx/module.h"
53 #include "wx/msw/private.h"
56 #include "wx/thread.h"
58 // define the array of MSG strutures
59 WX_DECLARE_OBJARRAY(MSG
, wxMsgArray
);
61 #include "wx/arrimpl.cpp"
63 WX_DEFINE_OBJARRAY(wxMsgArray
);
64 #endif // wxUSE_THREADS
66 #if wxUSE_WX_RESOURCES
67 #include "wx/resource.h"
71 #include "wx/tooltip.h"
72 #endif // wxUSE_TOOLTIPS
74 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
75 // compilers don't support it (missing headers, libs, ...)
76 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
80 #endif // broken compilers
89 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
93 #ifndef __WXMICROWIN__
94 #include "wx/msw/msvcrt.h"
97 // ----------------------------------------------------------------------------
98 // conditional compilation
99 // ----------------------------------------------------------------------------
101 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
102 // defined before) and shows us what common control features are available
103 // during the compile time (it doesn't mean that they will be available during
104 // the run-time, use GetComCtl32Version() to test for them!). The possible
107 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
108 // 0x0300 4.70 IE 3.x
109 // 0x0400 4.71 IE 4.0
110 // 0x0401 4.72 IE 4.01 and Win98
111 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
114 // minimal set of features by default
115 #define _WIN32_IE 0x0200
118 #if _WIN32_IE >= 0x0300 && !defined(__MINGW32__)
122 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 extern wxChar
*wxBuffer
;
127 extern wxList WXDLLEXPORT wxPendingDelete
;
128 #ifndef __WXMICROWIN__
129 extern void wxSetKeyboardHook(bool doIt
);
133 wxApp
*wxTheApp
= NULL
;
135 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
136 // with NR suffix - wxWindow::MSWCreate() supposes this
137 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
138 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
139 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
140 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
141 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
142 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
143 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
144 const wxChar
*wxPanelClassNameNR
= wxT("wxPanelClassNR");
145 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
146 const wxChar
*wxCanvasClassNameNR
= wxT("wxCanvasClassNR");
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 - if so, abort right now as it has no chance to
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.\nProgram aborted."),
206 _T("wxWindows Fatal Error"),
212 #endif // wxUSE_UNICODE
214 // Some people may wish to use this, but
215 // probably it shouldn't be here by default.
217 // wxRedirectIOToConsole();
220 wxBuffer
= new wxChar
[1500]; // FIXME
222 wxClassInfo::InitializeClasses();
225 wxPendingEventsLocker
= new wxCriticalSection
;
228 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
229 wxTheColourDatabase
->Initialize();
231 wxInitializeStockLists();
232 wxInitializeStockObjects();
234 #if wxUSE_WX_RESOURCES
235 wxInitializeResourceSystem();
238 wxBitmap::InitStandardHandlers();
240 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
241 InitCommonControls();
244 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
247 // for OLE, enlarge message queue to be as large as possible
249 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
253 // we need to initialize OLE library
254 if ( FAILED(::OleInitialize(NULL
)) )
255 wxLogError(_("Cannot initialize OLE"));
260 if (!Ctl3dRegister(wxhInstance
))
261 wxLogError(wxT("Cannot register CTL3D"));
263 Ctl3dAutoSubclass(wxhInstance
);
264 #endif // wxUSE_CTL3D
266 // VZ: these icons are not in wx.rc anyhow (but should they?)!
268 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
269 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
270 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
272 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
273 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
274 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
277 RegisterWindowClasses();
279 #ifndef __WXMICROWIN__
280 // Create the brush for disabling bitmap buttons
283 lb
.lbStyle
= BS_PATTERN
;
284 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
287 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
288 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
290 //else: wxWindows resources are probably not linked in
297 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
299 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
300 // PLEASE DO NOT ALTER THIS.
301 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
302 extern char wxDummyChar
;
303 if (wxDummyChar
) wxDummyChar
++;
306 #ifndef __WXMICROWIN__
307 wxSetKeyboardHook(TRUE
);
310 wxModule::RegisterModules();
311 if (!wxModule::InitializeModules())
316 // ---------------------------------------------------------------------------
317 // RegisterWindowClasses
318 // ---------------------------------------------------------------------------
320 // TODO we should only register classes really used by the app. For this it
321 // would be enough to just delay the class registration until an attempt
322 // to create a window of this class is made.
323 bool wxApp::RegisterWindowClasses()
327 // for each class we register one with CS_(V|H)REDRAW style and one
328 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
329 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
330 static const long styleNoRedraw
= CS_DBLCLKS
;
332 // the fields which are common to all classes
333 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
334 wndclass
.cbClsExtra
= 0;
335 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
336 wndclass
.hInstance
= wxhInstance
;
337 wndclass
.hIcon
= (HICON
) NULL
;
338 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
339 wndclass
.lpszMenuName
= NULL
;
341 // Register the frame window class.
342 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
343 wndclass
.lpszClassName
= wxFrameClassName
;
344 wndclass
.style
= styleNormal
;
346 if ( !RegisterClass(&wndclass
) )
348 wxLogLastError(wxT("RegisterClass(frame)"));
354 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
355 wndclass
.style
= styleNoRedraw
;
357 if ( !RegisterClass(&wndclass
) )
359 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
364 // Register the MDI frame window class.
365 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
366 wndclass
.lpszClassName
= wxMDIFrameClassName
;
367 wndclass
.style
= styleNormal
;
369 if ( !RegisterClass(&wndclass
) )
371 wxLogLastError(wxT("RegisterClass(MDI parent)"));
376 // "no redraw" MDI frame
377 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
378 wndclass
.style
= styleNoRedraw
;
380 if ( !RegisterClass(&wndclass
) )
382 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
387 // Register the MDI child frame window class.
388 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
389 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
390 wndclass
.style
= styleNormal
;
392 if ( !RegisterClass(&wndclass
) )
394 wxLogLastError(wxT("RegisterClass(MDI child)"));
399 // "no redraw" MDI child frame
400 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
401 wndclass
.style
= styleNoRedraw
;
403 if ( !RegisterClass(&wndclass
) )
405 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
410 // Register the panel window class.
411 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
412 wndclass
.lpszClassName
= wxPanelClassName
;
413 wndclass
.style
= styleNormal
;
415 if ( !RegisterClass(&wndclass
) )
417 wxLogLastError(wxT("RegisterClass(panel)"));
422 // Register the no redraw panel window class.
423 wndclass
.lpszClassName
= wxPanelClassNameNR
;
424 wndclass
.style
= styleNoRedraw
;
426 if ( !RegisterClass(&wndclass
) )
428 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
433 // Register the canvas and textsubwindow class name
434 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
435 wndclass
.lpszClassName
= wxCanvasClassName
;
437 if ( !RegisterClass(&wndclass
) )
439 wxLogLastError(wxT("RegisterClass(canvas)"));
444 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
445 wndclass
.style
= styleNoRedraw
;
446 if ( !RegisterClass(&wndclass
) )
448 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
456 // ---------------------------------------------------------------------------
457 // UnregisterWindowClasses
458 // ---------------------------------------------------------------------------
460 bool wxApp::UnregisterWindowClasses()
464 // frame window class.
465 if ( !UnregisterClass(wxFrameClassName
, wxhInstance
) )
467 wxLogLastError(wxT("UnregisterClass(frame)"));
473 if ( !UnregisterClass(wxFrameClassNameNoRedraw
, wxhInstance
) )
475 wxLogLastError(wxT("UnregisterClass(no redraw frame)"));
480 // MDI frame window class.
481 if ( !UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
483 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
488 // "no redraw" MDI frame
489 if ( !UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
491 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
496 // MDI child frame window class.
497 if ( !UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
499 wxLogLastError(wxT("UnregisterClass(MDI child)"));
504 // "no redraw" MDI child frame
505 if ( !UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
507 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
512 // panel window class.
513 if ( !UnregisterClass(wxPanelClassName
, wxhInstance
) )
515 wxLogLastError(wxT("UnregisterClass(panel)"));
520 // no redraw panel window class.
521 if ( !UnregisterClass(wxPanelClassNameNR
, wxhInstance
) )
523 wxLogLastError(wxT("UnregisterClass(no redraw panel)"));
528 // canvas and textsubwindow class name
529 if ( !UnregisterClass(wxCanvasClassName
, wxhInstance
) )
531 wxLogLastError(wxT("UnregisterClass(canvas)"));
536 if ( !UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
538 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
546 // ---------------------------------------------------------------------------
547 // Convert Windows to argc, argv style
548 // ---------------------------------------------------------------------------
550 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
554 wxString
cmdLine(lpCmdLine
);
557 // Get application name
558 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
559 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
564 wxStrcpy(name
, wxFileNameFromPath(name
));
565 wxStripExtension(name
);
566 wxTheApp
->SetAppName(name
);
569 // Treat strings enclosed in double-quotes as single arguments
571 int len
= cmdLine
.Length();
575 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
580 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
584 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
587 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
593 i
++; // Skip past 2nd quote
595 else // Unquoted argument
598 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
601 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
609 wxTheApp
->argv
= new wxChar
*[count
+ 1];
610 for (i
= 0; i
< count
; i
++)
612 wxString
arg(args
[i
]);
613 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
615 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
616 wxTheApp
->argc
= count
;
619 //// Cleans up any wxWindows internal structures left lying around
621 void wxApp::CleanUp()
626 // flush the logged messages if any and install a 'safer' log target: the
627 // default one (wxLogGui) can't be used after the resources are freed just
628 // below and the user suppliedo ne might be even more unsafe (using any
629 // wxWindows GUI function is unsafe starting from now)
630 wxLog::DontCreateOnDemand();
632 // this will flush the old messages if any
633 delete wxLog::SetActiveTarget(new wxLogStderr
);
636 // One last chance for pending objects to be cleaned up
637 wxTheApp
->DeletePendingObjects();
639 wxModule::CleanUpModules();
641 #if wxUSE_WX_RESOURCES
642 wxCleanUpResourceSystem();
644 // wxDefaultResourceTable->ClearTable();
647 wxDeleteStockObjects();
649 // Destroy all GDI lists, etc.
650 wxDeleteStockLists();
652 delete wxTheColourDatabase
;
653 wxTheColourDatabase
= NULL
;
655 wxBitmap::CleanUpHandlers();
660 //// WINDOWS-SPECIFIC CLEANUP
662 #ifndef __WXMICROWIN__
663 wxSetKeyboardHook(FALSE
);
670 if (wxSTD_FRAME_ICON
)
671 DestroyIcon(wxSTD_FRAME_ICON
);
672 if (wxSTD_MDICHILDFRAME_ICON
)
673 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
674 if (wxSTD_MDIPARENTFRAME_ICON
)
675 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
677 if (wxDEFAULT_FRAME_ICON
)
678 DestroyIcon(wxDEFAULT_FRAME_ICON
);
679 if (wxDEFAULT_MDICHILDFRAME_ICON
)
680 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
681 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
682 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
684 if ( wxDisableButtonBrush
)
685 ::DeleteObject( wxDisableButtonBrush
);
692 // for an EXE the classes are unregistered when it terminates but DLL may
693 // be loaded several times (load/unload/load) into the same process in
694 // which case the registration will fail after the first time if we don't
695 // unregister the classes now
696 UnregisterWindowClasses();
697 #endif // WXMAKINGDLL
700 Ctl3dUnregister(wxhInstance
);
703 delete wxWinHandleHash
;
705 // GL: I'm annoyed ... I don't know where to put this and I don't want to
706 // create a module for that as it's part of the core.
707 delete wxPendingEvents
;
710 delete wxPendingEventsLocker
;
711 // If we don't do the following, we get an apparent memory leak
713 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
714 #endif // wxUSE_VALIDATORS
715 #endif // wxUSE_THREADS
717 wxClassInfo::CleanUpClasses();
722 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
723 // At this point we want to check if there are any memory
724 // blocks that aren't part of the wxDebugContext itself,
725 // as a special case. Then when dumping we need to ignore
726 // wxDebugContext, too.
727 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
729 wxLogMessage(wxT("There were memory leaks."));
730 wxDebugContext::Dump();
731 wxDebugContext::PrintStatistics();
733 // wxDebugContext::SetStream(NULL, NULL);
737 // do it as the very last thing because everything else can log messages
738 delete wxLog::SetActiveTarget(NULL
);
742 //----------------------------------------------------------------------
743 // Entry point helpers, used by wxPython
744 //----------------------------------------------------------------------
746 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
748 return wxApp::Initialize();
751 int WXDLLEXPORT
wxEntryInitGui()
753 return wxTheApp
->OnInitGui();
756 void WXDLLEXPORT
wxEntryCleanup()
762 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
764 // temporarily disable this warning which would be generated in release builds
767 #pragma warning(disable: 4715) // not all control paths return a value
770 //----------------------------------------------------------------------
771 // Main wxWindows entry point
772 //----------------------------------------------------------------------
773 int wxEntry(WXHINSTANCE hInstance
,
774 WXHINSTANCE
WXUNUSED(hPrevInstance
),
779 // do check for memory leaks on program exit
780 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
781 // deallocated memory which may be used to simulate low-memory condition)
782 #ifndef __WXMICROWIN__
783 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
787 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
788 // This seems to be necessary since there are 'rogue'
789 // objects present at this point (perhaps global objects?)
790 // Setting a checkpoint will ignore them as far as the
791 // memory checking facility is concerned.
792 // Of course you may argue that memory allocated in globals should be
793 // checked, but this is a reasonable compromise.
794 wxDebugContext::SetCheckpoint();
798 // take everything into a try-except block to be able to call
799 // OnFatalException() if necessary
800 #if wxUSE_ON_FATAL_EXCEPTION
803 wxhInstance
= (HINSTANCE
) hInstance
;
805 if (!wxEntryStart(0,0))
808 // create the application object or ensure that one already exists
811 // The app may have declared a global application object, but we recommend
812 // the IMPLEMENT_APP macro is used instead, which sets an initializer
813 // function for delayed, dynamic app object construction.
814 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
815 wxT("No initializer - use IMPLEMENT_APP macro.") );
817 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
820 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
822 // save the WinMain() parameters
823 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
824 wxTheApp
->m_nCmdShow
= nCmdShow
;
826 // We really don't want timestamps by default, because it means
827 // we can't simply double-click on the error message and get to that
828 // line in the source. So VC++ at least, let's have a sensible default.
830 wxLog::SetTimestamp(NULL
);
835 // it is common to create a modal dialog in OnInit() (to ask/notify the
836 // user about something) but it wouldn't work if we don't change the
837 // "exit on delete last frame" flag here as when this dialog is
838 // deleted, the app would terminate (it was the last top level window
839 // as the main frame wasn't created yet!), so disable this behaviour
841 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
842 wxTheApp
->SetExitOnFrameDelete(FALSE
);
845 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
847 // restore the old flag value
848 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
855 retValue
= wxTheApp
->OnRun();
859 // we want to initialize, but not run or exit immediately.
863 //else: app initialization failed, so we skipped OnRun()
865 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
868 // Forcibly delete the window.
869 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
870 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
872 topWindow
->Close(TRUE
);
873 wxTheApp
->DeletePendingObjects();
878 wxTheApp
->SetTopWindow(NULL
);
888 #if wxUSE_ON_FATAL_EXCEPTION
890 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
891 : EXCEPTION_CONTINUE_SEARCH
) {
894 // give the user a chance to do something special about this
895 wxTheApp
->OnFatalException();
898 ::ExitProcess(3); // the same exit code as abort()
902 #endif // wxUSE_ON_FATAL_EXCEPTION
905 // restore warning state
907 #pragma warning(default: 4715) // not all control paths return a value
912 //----------------------------------------------------------------------
913 // Entry point for wxWindows + the App in a DLL
914 //----------------------------------------------------------------------
916 int wxEntry(WXHINSTANCE hInstance
)
918 wxhInstance
= (HINSTANCE
) hInstance
;
921 // The app may have declared a global application object, but we recommend
922 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
923 // for delayed, dynamic app object construction.
926 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
927 "No initializer - use IMPLEMENT_APP macro." );
929 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
932 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
935 wxTheApp
->argv
= NULL
;
941 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
942 if ( topWindow
&& topWindow
->GetHWND())
944 topWindow
->Show(TRUE
);
951 //// Static member initialization
953 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
959 m_printMode
= wxPRINT_WINDOWS
;
965 // Delete command-line args
967 for (i
= 0; i
< argc
; i
++)
974 bool wxApp::Initialized()
981 #else // Assume initialized if DLL (no way of telling)
987 * Get and process a message, returning FALSE if WM_QUIT
988 * received (and also set the flag telling the app to exit the main loop)
991 bool wxApp::DoMessage()
993 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
1001 else if ( rc
== -1 )
1003 // should never happen, but let's test for it nevertheless
1004 wxLogLastError(wxT("GetMessage"));
1009 wxASSERT_MSG( wxThread::IsMain(),
1010 wxT("only the main thread can process Windows messages") );
1012 static bool s_hadGuiLock
= TRUE
;
1013 static wxMsgArray s_aSavedMessages
;
1015 // if a secondary thread owns is doing GUI calls, save all messages for
1016 // later processing - we can't process them right now because it will
1017 // lead to recursive library calls (and we're not reentrant)
1018 if ( !wxGuiOwnedByMainThread() )
1020 s_hadGuiLock
= FALSE
;
1022 // leave out WM_COMMAND messages: too dangerous, sometimes
1023 // the message will be processed twice
1024 if ( !wxIsWaitingForThread() ||
1025 s_currentMsg
.message
!= WM_COMMAND
)
1027 s_aSavedMessages
.Add(s_currentMsg
);
1034 // have we just regained the GUI lock? if so, post all of the saved
1037 // FIXME of course, it's not _exactly_ the same as processing the
1038 // messages normally - expect some things to break...
1039 if ( !s_hadGuiLock
)
1041 s_hadGuiLock
= TRUE
;
1043 size_t count
= s_aSavedMessages
.Count();
1044 for ( size_t n
= 0; n
< count
; n
++ )
1046 MSG
& msg
= s_aSavedMessages
[n
];
1048 if ( !ProcessMessage((WXMSG
*)&msg
) )
1050 ::TranslateMessage(&msg
);
1051 ::DispatchMessage(&msg
);
1055 s_aSavedMessages
.Empty();
1058 #endif // wxUSE_THREADS
1060 // Process the message
1061 DoMessage((WXMSG
*)&s_currentMsg
);
1067 void wxApp::DoMessage(WXMSG
*pMsg
)
1069 if ( !ProcessMessage(pMsg
) )
1071 ::TranslateMessage((MSG
*)pMsg
);
1072 ::DispatchMessage((MSG
*)pMsg
);
1077 * Keep trying to process messages until WM_QUIT
1080 * If there are messages to be processed, they will all be
1081 * processed and OnIdle will not be called.
1082 * When there are no more messages, OnIdle is called.
1083 * If OnIdle requests more time,
1084 * it will be repeatedly called so long as there are no pending messages.
1085 * A 'feature' of this is that once OnIdle has decided that no more processing
1086 * is required, then it won't get processing time until further messages
1087 * are processed (it'll sit in DoMessage).
1090 int wxApp::MainLoop()
1094 while ( m_keepGoing
)
1097 wxMutexGuiLeaveOrEnter();
1098 #endif // wxUSE_THREADS
1100 while ( !Pending() && ProcessIdle() )
1103 // a message came or no more idle processing to do
1107 return s_currentMsg
.wParam
;
1110 // Returns TRUE if more time is needed.
1111 bool wxApp::ProcessIdle()
1114 event
.SetEventObject(this);
1115 ProcessEvent(event
);
1117 return event
.MoreRequested();
1120 void wxApp::ExitMainLoop()
1122 // VZ: why not ::PostQuitMessage()?
1123 m_keepGoing
= FALSE
;
1126 bool wxApp::Pending()
1128 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1131 void wxApp::Dispatch()
1137 * Give all windows a chance to preprocess
1138 * the message. Some may have accelerator tables, or have
1139 * MDI complications.
1142 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1144 MSG
*msg
= (MSG
*)wxmsg
;
1145 HWND hwnd
= msg
->hwnd
;
1146 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1148 // this may happen if the event occured in a standard modeless dialog (the
1149 // only example of which I know of is the find/replace dialog) - then call
1150 // IsDialogMessage() to make TAB navigation in it work
1153 // we need to find the dialog containing this control as
1154 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1155 // them) if we call it for the control itself
1156 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1158 hwnd
= ::GetParent(hwnd
);
1161 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1165 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1166 // popup the tooltip bubbles
1167 if ( (msg
->message
== WM_MOUSEMOVE
) )
1169 wxToolTip
*tt
= wndThis
->GetToolTip();
1172 tt
->RelayEvent(wxmsg
);
1175 #endif // wxUSE_TOOLTIPS
1177 // allow the window to prevent certain messages from being
1178 // translated/processed (this is currently used by wxTextCtrl to always
1179 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1180 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1185 // try translations first: the accelerators override everything
1188 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1190 if ( wnd
->MSWTranslateMessage(wxmsg
))
1193 // stop at first top level window, i.e. don't try to process the key
1194 // strokes originating in a dialog using the accelerators of the parent
1195 // frame - this doesn't make much sense
1196 if ( wnd
->IsTopLevel() )
1200 // now try the other hooks (kbd navigation is handled here): we start from
1201 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1203 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1205 if ( wnd
->MSWProcessMessage(wxmsg
) )
1209 // no special preprocessing for this message, dispatch it normally
1213 void wxApp::OnIdle(wxIdleEvent
& event
)
1215 static bool s_inOnIdle
= FALSE
;
1217 // Avoid recursion (via ProcessEvent default case)
1223 // If there are pending events, we must process them: pending events
1224 // are either events to the threads other than main or events posted
1225 // with wxPostEvent() functions
1226 // GRG: I have moved this here so that all pending events are processed
1227 // before starting to delete any objects. This behaves better (in
1228 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1229 // behaviour. Changed Feb/2000 before 2.1.14
1230 ProcessPendingEvents();
1232 // 'Garbage' collection of windows deleted with Close().
1233 DeletePendingObjects();
1236 // flush the logged messages if any
1237 wxLog::FlushActive();
1240 #if wxUSE_DC_CACHEING
1241 // automated DC cache management: clear the cached DCs and bitmap
1242 // if it's likely that the app has finished with them, that is, we
1243 // get an idle event and we're not dragging anything.
1244 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1246 #endif // wxUSE_DC_CACHEING
1248 // Send OnIdle events to all windows
1249 if ( SendIdleEvents() )
1251 // SendIdleEvents() returns TRUE if at least one window requested more
1253 event
.RequestMore(TRUE
);
1259 // Send idle event to all top-level windows
1260 bool wxApp::SendIdleEvents()
1262 bool needMore
= FALSE
;
1264 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1267 wxWindow
* win
= node
->GetData();
1268 if (SendIdleEvents(win
))
1270 node
= node
->GetNext();
1276 // Send idle event to window and all subwindows
1277 bool wxApp::SendIdleEvents(wxWindow
* win
)
1279 bool needMore
= FALSE
;
1282 event
.SetEventObject(win
);
1283 win
->GetEventHandler()->ProcessEvent(event
);
1285 if (event
.MoreRequested())
1288 wxNode
* node
= win
->GetChildren().First();
1291 wxWindow
* win
= (wxWindow
*) node
->Data();
1292 if (SendIdleEvents(win
))
1295 node
= node
->Next();
1300 void wxApp::DeletePendingObjects()
1302 wxNode
*node
= wxPendingDelete
.First();
1305 wxObject
*obj
= (wxObject
*)node
->Data();
1309 if (wxPendingDelete
.Member(obj
))
1312 // Deleting one object may have deleted other pending
1313 // objects, so start from beginning of list again.
1314 node
= wxPendingDelete
.First();
1318 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1321 GetTopWindow()->Close(TRUE
);
1324 // Default behaviour: close the application with prompts. The
1325 // user can veto the close, and therefore the end session.
1326 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1330 if (!GetTopWindow()->Close(!event
.CanVeto()))
1336 int wxApp::GetComCtl32Version()
1338 #ifdef __WXMICROWIN__
1342 static int s_verComCtl32
= -1;
1344 wxCRIT_SECT_DECLARE(csComCtl32
);
1345 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1347 if ( s_verComCtl32
== -1 )
1349 // initally assume no comctl32.dll at all
1353 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1355 // if so, then we can check for the version
1356 if ( hModuleComCtl32
)
1358 // try to use DllGetVersion() if available in _headers_
1359 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1360 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1361 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1362 if ( pfnDllGetVersion
)
1365 dvi
.cbSize
= sizeof(dvi
);
1367 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1370 wxLogApiError(_T("DllGetVersion"), hr
);
1374 // this is incompatible with _WIN32_IE values, but
1375 // compatible with the other values returned by
1376 // GetComCtl32Version()
1377 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1382 // DllGetVersion() unavailable either during compile or
1383 // run-time, try to guess the version otherwise
1384 if ( !s_verComCtl32
)
1386 // InitCommonControlsEx is unique to 4.70 and later
1387 FARPROC theProc
= ::GetProcAddress
1390 "InitCommonControlsEx"
1395 // not found, must be 4.00
1396 s_verComCtl32
= 400;
1400 // many symbols appeared in comctl32 4.71, could use
1401 // any of them except may be DllInstall
1402 theProc
= ::GetProcAddress
1409 // not found, must be 4.70
1410 s_verComCtl32
= 470;
1414 // found, must be 4.71
1415 s_verComCtl32
= 471;
1422 return s_verComCtl32
;
1428 wxLogError(_("Fatal error: exiting"));
1434 // Yield to incoming messages
1436 bool wxApp::Yield(bool onlyIfNeeded
)
1439 static bool s_inYield
= FALSE
;
1441 // disable log flushing from here because a call to wxYield() shouldn't
1442 // normally result in message boxes popping up &c
1447 if ( !onlyIfNeeded
)
1449 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1457 // we don't want to process WM_QUIT from here - it should be processed in
1458 // the main event loop in order to stop it
1460 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1461 msg
.message
!= WM_QUIT
)
1464 wxMutexGuiLeaveOrEnter();
1465 #endif // wxUSE_THREADS
1467 if ( !wxTheApp
->DoMessage() )
1471 // if there are pending events, we must process them.
1472 ProcessPendingEvents();
1474 // let the logs be flashed again
1482 bool wxHandleFatalExceptions(bool doit
)
1484 #if wxUSE_ON_FATAL_EXCEPTION
1485 // assume this can only be called from the main thread
1486 gs_handleExceptions
= doit
;
1490 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1497 //-----------------------------------------------------------------------------
1499 //-----------------------------------------------------------------------------
1503 // Send the top window a dummy message so idle handler processing will
1504 // start up again. Doing it this way ensures that the idle handler
1505 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1506 // the same for the main app thread only)
1507 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1510 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1512 // should never happen
1513 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1518 //-----------------------------------------------------------------------------
1521 wxApp::GetStdIcon(int which
) const
1525 case wxICON_INFORMATION
:
1526 return wxIcon("wxICON_INFO");
1528 case wxICON_QUESTION
:
1529 return wxIcon("wxICON_QUESTION");
1531 case wxICON_EXCLAMATION
:
1532 return wxIcon("wxICON_WARNING");
1535 wxFAIL_MSG(wxT("requested non existent standard icon"));
1536 // still fall through
1539 return wxIcon("wxICON_ERROR");
1543 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1544 // if in a separate file. So include it here to ensure it's linked.
1545 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))