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 wxBuffer
= new wxChar
[1500]; // FIXME
218 wxClassInfo::InitializeClasses();
221 wxPendingEventsLocker
= new wxCriticalSection
;
224 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
225 wxTheColourDatabase
->Initialize();
227 wxInitializeStockLists();
228 wxInitializeStockObjects();
230 #if wxUSE_WX_RESOURCES
231 wxInitializeResourceSystem();
234 wxBitmap::InitStandardHandlers();
236 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
237 InitCommonControls();
240 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
243 // for OLE, enlarge message queue to be as large as possible
245 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
250 // we need to initialize OLE library
251 if ( FAILED(::OleInitialize(NULL
)) )
252 wxLogError(_("Cannot initialize OLE"));
258 if (!Ctl3dRegister(wxhInstance
))
259 wxLogError(wxT("Cannot register CTL3D"));
261 Ctl3dAutoSubclass(wxhInstance
);
262 #endif // wxUSE_CTL3D
264 // VZ: these icons are not in wx.rc anyhow (but should they?)!
266 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
267 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
268 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
270 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
271 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
272 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
275 RegisterWindowClasses();
277 #ifndef __WXMICROWIN__
278 // Create the brush for disabling bitmap buttons
281 lb
.lbStyle
= BS_PATTERN
;
283 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
286 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
287 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
289 //else: wxWindows resources are probably not linked in
296 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
298 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
299 // PLEASE DO NOT ALTER THIS.
300 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
301 extern char wxDummyChar
;
302 if (wxDummyChar
) wxDummyChar
++;
305 #ifndef __WXMICROWIN__
306 wxSetKeyboardHook(TRUE
);
309 wxModule::RegisterModules();
310 if (!wxModule::InitializeModules())
315 // ---------------------------------------------------------------------------
316 // RegisterWindowClasses
317 // ---------------------------------------------------------------------------
319 // TODO we should only register classes really used by the app. For this it
320 // would be enough to just delay the class registration until an attempt
321 // to create a window of this class is made.
322 bool wxApp::RegisterWindowClasses()
326 // for each class we register one with CS_(V|H)REDRAW style and one
327 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
328 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
329 static const long styleNoRedraw
= CS_DBLCLKS
;
331 // the fields which are common to all classes
332 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
333 wndclass
.cbClsExtra
= 0;
334 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
335 wndclass
.hInstance
= wxhInstance
;
336 wndclass
.hIcon
= (HICON
) NULL
;
337 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
338 wndclass
.lpszMenuName
= NULL
;
340 // Register the frame window class.
341 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
342 wndclass
.lpszClassName
= wxFrameClassName
;
343 wndclass
.style
= styleNormal
;
345 if ( !RegisterClass(&wndclass
) )
347 wxLogLastError(wxT("RegisterClass(frame)"));
353 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
354 wndclass
.style
= styleNoRedraw
;
356 if ( !RegisterClass(&wndclass
) )
358 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
363 // Register the MDI frame window class.
364 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
365 wndclass
.lpszClassName
= wxMDIFrameClassName
;
366 wndclass
.style
= styleNormal
;
368 if ( !RegisterClass(&wndclass
) )
370 wxLogLastError(wxT("RegisterClass(MDI parent)"));
375 // "no redraw" MDI frame
376 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
377 wndclass
.style
= styleNoRedraw
;
379 if ( !RegisterClass(&wndclass
) )
381 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
386 // Register the MDI child frame window class.
387 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
388 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
389 wndclass
.style
= styleNormal
;
391 if ( !RegisterClass(&wndclass
) )
393 wxLogLastError(wxT("RegisterClass(MDI child)"));
398 // "no redraw" MDI child frame
399 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
400 wndclass
.style
= styleNoRedraw
;
402 if ( !RegisterClass(&wndclass
) )
404 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
409 // Register the panel window class.
410 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
411 wndclass
.lpszClassName
= wxPanelClassName
;
412 wndclass
.style
= styleNormal
;
414 if ( !RegisterClass(&wndclass
) )
416 wxLogLastError(wxT("RegisterClass(panel)"));
421 // Register the no redraw panel window class.
422 wndclass
.lpszClassName
= wxPanelClassNameNR
;
423 wndclass
.style
= styleNoRedraw
;
425 if ( !RegisterClass(&wndclass
) )
427 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
432 // Register the canvas and textsubwindow class name
433 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
434 wndclass
.lpszClassName
= wxCanvasClassName
;
436 if ( !RegisterClass(&wndclass
) )
438 wxLogLastError(wxT("RegisterClass(canvas)"));
443 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
444 wndclass
.style
= styleNoRedraw
;
445 if ( !RegisterClass(&wndclass
) )
447 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
455 // ---------------------------------------------------------------------------
456 // UnregisterWindowClasses
457 // ---------------------------------------------------------------------------
459 bool wxApp::UnregisterWindowClasses()
463 #ifndef __WXMICROWIN__
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)"));
547 // ---------------------------------------------------------------------------
548 // Convert Windows to argc, argv style
549 // ---------------------------------------------------------------------------
551 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine
)
553 // break the command line in words
555 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine
));
557 // +1 here for the program name
558 argc
= args
.GetCount() + 1;
560 // and +1 here for the terminating NULL
561 argv
= new wxChar
*[argc
+ 1];
563 argv
[0] = new wxChar
[260]; // 260 is MAX_PATH value from windef.h
564 ::GetModuleFileName(wxhInstance
, argv
[0], 260);
566 // also set the app name from argv[0]
568 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
572 // copy all the other arguments to wxApp::argv[]
573 for ( int i
= 1; i
< argc
; i
++ )
575 argv
[i
] = copystring(args
[i
- 1]);
578 // argv[] must be NULL-terminated
582 //// Cleans up any wxWindows internal structures left lying around
584 void wxApp::CleanUp()
589 // flush the logged messages if any and install a 'safer' log target: the
590 // default one (wxLogGui) can't be used after the resources are freed just
591 // below and the user suppliedo ne might be even more unsafe (using any
592 // wxWindows GUI function is unsafe starting from now)
593 wxLog::DontCreateOnDemand();
595 // this will flush the old messages if any
596 delete wxLog::SetActiveTarget(new wxLogStderr
);
599 // One last chance for pending objects to be cleaned up
600 wxTheApp
->DeletePendingObjects();
602 wxModule::CleanUpModules();
604 #if wxUSE_WX_RESOURCES
605 wxCleanUpResourceSystem();
607 // wxDefaultResourceTable->ClearTable();
610 wxDeleteStockObjects();
612 // Destroy all GDI lists, etc.
613 wxDeleteStockLists();
615 delete wxTheColourDatabase
;
616 wxTheColourDatabase
= NULL
;
618 wxBitmap::CleanUpHandlers();
623 //// WINDOWS-SPECIFIC CLEANUP
625 #ifndef __WXMICROWIN__
626 wxSetKeyboardHook(FALSE
);
633 if (wxSTD_FRAME_ICON
)
634 DestroyIcon(wxSTD_FRAME_ICON
);
635 if (wxSTD_MDICHILDFRAME_ICON
)
636 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
637 if (wxSTD_MDIPARENTFRAME_ICON
)
638 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
640 if (wxDEFAULT_FRAME_ICON
)
641 DestroyIcon(wxDEFAULT_FRAME_ICON
);
642 if (wxDEFAULT_MDICHILDFRAME_ICON
)
643 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
644 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
645 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
647 if ( wxDisableButtonBrush
)
648 ::DeleteObject( wxDisableButtonBrush
);
655 // for an EXE the classes are unregistered when it terminates but DLL may
656 // be loaded several times (load/unload/load) into the same process in
657 // which case the registration will fail after the first time if we don't
658 // unregister the classes now
659 UnregisterWindowClasses();
660 #endif // WXMAKINGDLL
663 Ctl3dUnregister(wxhInstance
);
666 delete wxWinHandleHash
;
668 // GL: I'm annoyed ... I don't know where to put this and I don't want to
669 // create a module for that as it's part of the core.
670 delete wxPendingEvents
;
673 delete wxPendingEventsLocker
;
674 // If we don't do the following, we get an apparent memory leak
676 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
677 #endif // wxUSE_VALIDATORS
678 #endif // wxUSE_THREADS
680 wxClassInfo::CleanUpClasses();
685 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
686 // At this point we want to check if there are any memory
687 // blocks that aren't part of the wxDebugContext itself,
688 // as a special case. Then when dumping we need to ignore
689 // wxDebugContext, too.
690 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
692 wxLogMessage(wxT("There were memory leaks."));
693 wxDebugContext::Dump();
694 wxDebugContext::PrintStatistics();
696 // wxDebugContext::SetStream(NULL, NULL);
700 // do it as the very last thing because everything else can log messages
701 delete wxLog::SetActiveTarget(NULL
);
705 //----------------------------------------------------------------------
706 // Entry point helpers, used by wxPython
707 //----------------------------------------------------------------------
709 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
711 return wxApp::Initialize();
714 int WXDLLEXPORT
wxEntryInitGui()
716 return wxTheApp
->OnInitGui();
719 void WXDLLEXPORT
wxEntryCleanup()
725 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
727 // temporarily disable this warning which would be generated in release builds
730 #pragma warning(disable: 4715) // not all control paths return a value
733 //----------------------------------------------------------------------
734 // Main wxWindows entry point
735 //----------------------------------------------------------------------
736 int wxEntry(WXHINSTANCE hInstance
,
737 WXHINSTANCE
WXUNUSED(hPrevInstance
),
742 // do check for memory leaks on program exit
743 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
744 // deallocated memory which may be used to simulate low-memory condition)
745 #ifndef __WXMICROWIN__
746 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
750 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
751 // This seems to be necessary since there are 'rogue'
752 // objects present at this point (perhaps global objects?)
753 // Setting a checkpoint will ignore them as far as the
754 // memory checking facility is concerned.
755 // Of course you may argue that memory allocated in globals should be
756 // checked, but this is a reasonable compromise.
757 wxDebugContext::SetCheckpoint();
761 // take everything into a try-except block to be able to call
762 // OnFatalException() if necessary
763 #if wxUSE_ON_FATAL_EXCEPTION
766 wxhInstance
= (HINSTANCE
) hInstance
;
768 if (!wxEntryStart(0,0))
771 // create the application object or ensure that one already exists
774 // The app may have declared a global application object, but we recommend
775 // the IMPLEMENT_APP macro is used instead, which sets an initializer
776 // function for delayed, dynamic app object construction.
777 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
778 wxT("No initializer - use IMPLEMENT_APP macro.") );
780 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
783 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
785 // save the WinMain() parameters
786 if (lpCmdLine
) // MicroWindows passes NULL
787 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
788 wxTheApp
->m_nCmdShow
= nCmdShow
;
790 // We really don't want timestamps by default, because it means
791 // we can't simply double-click on the error message and get to that
792 // line in the source. So VC++ at least, let's have a sensible default.
794 wxLog::SetTimestamp(NULL
);
799 // it is common to create a modal dialog in OnInit() (to ask/notify the
800 // user about something) but it wouldn't work if we don't change the
801 // "exit on delete last frame" flag here as when this dialog is
802 // deleted, the app would terminate (it was the last top level window
803 // as the main frame wasn't created yet!), so disable this behaviour
805 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
806 wxTheApp
->SetExitOnFrameDelete(FALSE
);
809 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
811 // restore the old flag value
812 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
819 retValue
= wxTheApp
->OnRun();
823 // we want to initialize, but not run or exit immediately.
827 //else: app initialization failed, so we skipped OnRun()
829 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
832 // Forcibly delete the window.
833 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
834 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
836 topWindow
->Close(TRUE
);
837 wxTheApp
->DeletePendingObjects();
842 wxTheApp
->SetTopWindow(NULL
);
852 #if wxUSE_ON_FATAL_EXCEPTION
854 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
855 : EXCEPTION_CONTINUE_SEARCH
) {
858 // give the user a chance to do something special about this
859 wxTheApp
->OnFatalException();
862 ::ExitProcess(3); // the same exit code as abort()
866 #endif // wxUSE_ON_FATAL_EXCEPTION
869 // restore warning state
871 #pragma warning(default: 4715) // not all control paths return a value
876 //----------------------------------------------------------------------
877 // Entry point for wxWindows + the App in a DLL
878 //----------------------------------------------------------------------
880 int wxEntry(WXHINSTANCE hInstance
)
882 wxhInstance
= (HINSTANCE
) hInstance
;
885 // The app may have declared a global application object, but we recommend
886 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
887 // for delayed, dynamic app object construction.
890 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
891 "No initializer - use IMPLEMENT_APP macro." );
893 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
896 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
899 wxTheApp
->argv
= NULL
;
905 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
906 if ( topWindow
&& topWindow
->GetHWND())
908 topWindow
->Show(TRUE
);
915 //// Static member initialization
917 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
923 m_printMode
= wxPRINT_WINDOWS
;
929 // Delete command-line args
931 for (i
= 0; i
< argc
; i
++)
938 bool wxApp::Initialized()
945 #else // Assume initialized if DLL (no way of telling)
951 * Get and process a message, returning FALSE if WM_QUIT
952 * received (and also set the flag telling the app to exit the main loop)
955 bool wxApp::DoMessage()
957 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
967 // should never happen, but let's test for it nevertheless
968 wxLogLastError(wxT("GetMessage"));
973 wxASSERT_MSG( wxThread::IsMain(),
974 wxT("only the main thread can process Windows messages") );
976 static bool s_hadGuiLock
= TRUE
;
977 static wxMsgArray s_aSavedMessages
;
979 // if a secondary thread owns is doing GUI calls, save all messages for
980 // later processing - we can't process them right now because it will
981 // lead to recursive library calls (and we're not reentrant)
982 if ( !wxGuiOwnedByMainThread() )
984 s_hadGuiLock
= FALSE
;
986 // leave out WM_COMMAND messages: too dangerous, sometimes
987 // the message will be processed twice
988 if ( !wxIsWaitingForThread() ||
989 s_currentMsg
.message
!= WM_COMMAND
)
991 s_aSavedMessages
.Add(s_currentMsg
);
998 // have we just regained the GUI lock? if so, post all of the saved
1001 // FIXME of course, it's not _exactly_ the same as processing the
1002 // messages normally - expect some things to break...
1003 if ( !s_hadGuiLock
)
1005 s_hadGuiLock
= TRUE
;
1007 size_t count
= s_aSavedMessages
.Count();
1008 for ( size_t n
= 0; n
< count
; n
++ )
1010 MSG
& msg
= s_aSavedMessages
[n
];
1012 if ( !ProcessMessage((WXMSG
*)&msg
) )
1014 ::TranslateMessage(&msg
);
1015 ::DispatchMessage(&msg
);
1019 s_aSavedMessages
.Empty();
1022 #endif // wxUSE_THREADS
1024 // Process the message
1025 DoMessage((WXMSG
*)&s_currentMsg
);
1031 void wxApp::DoMessage(WXMSG
*pMsg
)
1033 if ( !ProcessMessage(pMsg
) )
1035 ::TranslateMessage((MSG
*)pMsg
);
1036 ::DispatchMessage((MSG
*)pMsg
);
1041 * Keep trying to process messages until WM_QUIT
1044 * If there are messages to be processed, they will all be
1045 * processed and OnIdle will not be called.
1046 * When there are no more messages, OnIdle is called.
1047 * If OnIdle requests more time,
1048 * it will be repeatedly called so long as there are no pending messages.
1049 * A 'feature' of this is that once OnIdle has decided that no more processing
1050 * is required, then it won't get processing time until further messages
1051 * are processed (it'll sit in DoMessage).
1054 int wxApp::MainLoop()
1058 while ( m_keepGoing
)
1061 wxMutexGuiLeaveOrEnter();
1062 #endif // wxUSE_THREADS
1064 while ( !Pending() && ProcessIdle() )
1067 // a message came or no more idle processing to do
1071 return s_currentMsg
.wParam
;
1074 // Returns TRUE if more time is needed.
1075 bool wxApp::ProcessIdle()
1078 event
.SetEventObject(this);
1079 ProcessEvent(event
);
1081 return event
.MoreRequested();
1084 void wxApp::ExitMainLoop()
1086 // VZ: why not ::PostQuitMessage()?
1087 m_keepGoing
= FALSE
;
1090 bool wxApp::Pending()
1092 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1095 void wxApp::Dispatch()
1101 * Give all windows a chance to preprocess
1102 * the message. Some may have accelerator tables, or have
1103 * MDI complications.
1106 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1108 MSG
*msg
= (MSG
*)wxmsg
;
1109 HWND hwnd
= msg
->hwnd
;
1110 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hwnd
);
1112 // this may happen if the event occured in a standard modeless dialog (the
1113 // only example of which I know of is the find/replace dialog) - then call
1114 // IsDialogMessage() to make TAB navigation in it work
1117 // we need to find the dialog containing this control as
1118 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1119 // them) if we call it for the control itself
1120 while ( hwnd
&& ::GetWindowLong(hwnd
, GWL_STYLE
) & WS_CHILD
)
1122 hwnd
= ::GetParent(hwnd
);
1125 return hwnd
&& ::IsDialogMessage(hwnd
, msg
) != 0;
1129 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1130 // popup the tooltip bubbles
1131 if ( (msg
->message
== WM_MOUSEMOVE
) )
1133 wxToolTip
*tt
= wndThis
->GetToolTip();
1136 tt
->RelayEvent(wxmsg
);
1139 #endif // wxUSE_TOOLTIPS
1141 // allow the window to prevent certain messages from being
1142 // translated/processed (this is currently used by wxTextCtrl to always
1143 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1144 if ( !wndThis
->MSWShouldPreProcessMessage(wxmsg
) )
1149 // try translations first: the accelerators override everything
1152 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1154 if ( wnd
->MSWTranslateMessage(wxmsg
))
1157 // stop at first top level window, i.e. don't try to process the key
1158 // strokes originating in a dialog using the accelerators of the parent
1159 // frame - this doesn't make much sense
1160 if ( wnd
->IsTopLevel() )
1164 // now try the other hooks (kbd navigation is handled here): we start from
1165 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1167 for ( wnd
= wndThis
->GetParent(); wnd
; wnd
= wnd
->GetParent() )
1169 if ( wnd
->MSWProcessMessage(wxmsg
) )
1173 // no special preprocessing for this message, dispatch it normally
1177 void wxApp::OnIdle(wxIdleEvent
& event
)
1179 static bool s_inOnIdle
= FALSE
;
1181 // Avoid recursion (via ProcessEvent default case)
1187 // If there are pending events, we must process them: pending events
1188 // are either events to the threads other than main or events posted
1189 // with wxPostEvent() functions
1190 // GRG: I have moved this here so that all pending events are processed
1191 // before starting to delete any objects. This behaves better (in
1192 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1193 // behaviour. Changed Feb/2000 before 2.1.14
1194 ProcessPendingEvents();
1196 // 'Garbage' collection of windows deleted with Close().
1197 DeletePendingObjects();
1200 // flush the logged messages if any
1201 wxLog::FlushActive();
1204 #if wxUSE_DC_CACHEING
1205 // automated DC cache management: clear the cached DCs and bitmap
1206 // if it's likely that the app has finished with them, that is, we
1207 // get an idle event and we're not dragging anything.
1208 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
1210 #endif // wxUSE_DC_CACHEING
1212 // Send OnIdle events to all windows
1213 if ( SendIdleEvents() )
1215 // SendIdleEvents() returns TRUE if at least one window requested more
1217 event
.RequestMore(TRUE
);
1223 // Send idle event to all top-level windows
1224 bool wxApp::SendIdleEvents()
1226 bool needMore
= FALSE
;
1228 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1231 wxWindow
* win
= node
->GetData();
1232 if (SendIdleEvents(win
))
1234 node
= node
->GetNext();
1240 // Send idle event to window and all subwindows
1241 bool wxApp::SendIdleEvents(wxWindow
* win
)
1243 bool needMore
= FALSE
;
1246 event
.SetEventObject(win
);
1247 win
->GetEventHandler()->ProcessEvent(event
);
1249 if (event
.MoreRequested())
1252 wxNode
* node
= win
->GetChildren().First();
1255 wxWindow
* win
= (wxWindow
*) node
->Data();
1256 if (SendIdleEvents(win
))
1259 node
= node
->Next();
1264 void wxApp::DeletePendingObjects()
1266 wxNode
*node
= wxPendingDelete
.First();
1269 wxObject
*obj
= (wxObject
*)node
->Data();
1273 if (wxPendingDelete
.Member(obj
))
1276 // Deleting one object may have deleted other pending
1277 // objects, so start from beginning of list again.
1278 node
= wxPendingDelete
.First();
1282 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1285 GetTopWindow()->Close(TRUE
);
1288 // Default behaviour: close the application with prompts. The
1289 // user can veto the close, and therefore the end session.
1290 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1294 if (!GetTopWindow()->Close(!event
.CanVeto()))
1300 int wxApp::GetComCtl32Version()
1302 #ifdef __WXMICROWIN__
1306 static int s_verComCtl32
= -1;
1308 wxCRIT_SECT_DECLARE(csComCtl32
);
1309 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1311 if ( s_verComCtl32
== -1 )
1313 // initally assume no comctl32.dll at all
1317 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1319 // if so, then we can check for the version
1320 if ( hModuleComCtl32
)
1322 // try to use DllGetVersion() if available in _headers_
1323 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1324 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1325 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1326 if ( pfnDllGetVersion
)
1329 dvi
.cbSize
= sizeof(dvi
);
1331 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1334 wxLogApiError(_T("DllGetVersion"), hr
);
1338 // this is incompatible with _WIN32_IE values, but
1339 // compatible with the other values returned by
1340 // GetComCtl32Version()
1341 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1346 // DllGetVersion() unavailable either during compile or
1347 // run-time, try to guess the version otherwise
1348 if ( !s_verComCtl32
)
1350 // InitCommonControlsEx is unique to 4.70 and later
1351 FARPROC theProc
= ::GetProcAddress
1354 "InitCommonControlsEx"
1359 // not found, must be 4.00
1360 s_verComCtl32
= 400;
1364 // many symbols appeared in comctl32 4.71, could use
1365 // any of them except may be DllInstall
1366 theProc
= ::GetProcAddress
1373 // not found, must be 4.70
1374 s_verComCtl32
= 470;
1378 // found, must be 4.71
1379 s_verComCtl32
= 471;
1386 return s_verComCtl32
;
1392 wxLogError(_("Fatal error: exiting"));
1398 // Yield to incoming messages
1400 bool wxApp::Yield(bool onlyIfNeeded
)
1403 static bool s_inYield
= FALSE
;
1405 // disable log flushing from here because a call to wxYield() shouldn't
1406 // normally result in message boxes popping up &c
1411 if ( !onlyIfNeeded
)
1413 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1421 // we don't want to process WM_QUIT from here - it should be processed in
1422 // the main event loop in order to stop it
1424 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1425 msg
.message
!= WM_QUIT
)
1428 wxMutexGuiLeaveOrEnter();
1429 #endif // wxUSE_THREADS
1431 if ( !wxTheApp
->DoMessage() )
1435 // if there are pending events, we must process them.
1436 ProcessPendingEvents();
1438 // let the logs be flashed again
1446 bool wxHandleFatalExceptions(bool doit
)
1448 #if wxUSE_ON_FATAL_EXCEPTION
1449 // assume this can only be called from the main thread
1450 gs_handleExceptions
= doit
;
1454 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1461 //-----------------------------------------------------------------------------
1463 //-----------------------------------------------------------------------------
1467 // Send the top window a dummy message so idle handler processing will
1468 // start up again. Doing it this way ensures that the idle handler
1469 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1470 // the same for the main app thread only)
1471 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1474 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1476 // should never happen
1477 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1482 //-----------------------------------------------------------------------------
1485 wxApp::GetStdIcon(int which
) const
1489 case wxICON_INFORMATION
:
1490 return wxIcon("wxICON_INFO");
1492 case wxICON_QUESTION
:
1493 return wxIcon("wxICON_QUESTION");
1495 case wxICON_EXCLAMATION
:
1496 return wxIcon("wxICON_WARNING");
1499 wxFAIL_MSG(wxT("requested non existent standard icon"));
1500 // still fall through
1503 return wxIcon("wxICON_ERROR");
1507 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1508 // if in a separate file. So include it here to ensure it's linked.
1509 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))