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
122 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 extern wxChar
*wxBuffer
;
127 extern wxList
*wxWinHandleList
;
128 extern wxList WXDLLEXPORT wxPendingDelete
;
129 #ifndef __WXMICROWIN__
130 extern void wxSetKeyboardHook(bool doIt
);
134 wxApp
*wxTheApp
= NULL
;
136 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
137 // with NR suffix - wxWindow::MSWCreate() supposes this
138 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
139 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
140 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
141 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
142 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
143 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
144 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
145 const wxChar
*wxPanelClassNameNR
= wxT("wxPanelClassNR");
146 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
147 const wxChar
*wxCanvasClassNameNR
= wxT("wxCanvasClassNR");
149 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
150 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
151 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
153 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
154 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
155 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
157 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
159 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
161 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
162 // needs compiler support for Win32 SEH. Others (especially Borland)
163 // probably have it too, but I'm not sure about how it works
164 // JACS: get 'Cannot use __try in functions that require unwinding
165 // in Unicode mode, so disabling.
166 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
167 #undef wxUSE_ON_FATAL_EXCEPTION
168 #define wxUSE_ON_FATAL_EXCEPTION 0
171 #if wxUSE_ON_FATAL_EXCEPTION
172 static bool gs_handleExceptions
= FALSE
;
175 // ===========================================================================
177 // ===========================================================================
179 // ---------------------------------------------------------------------------
181 // ---------------------------------------------------------------------------
183 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
185 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
186 EVT_IDLE(wxApp::OnIdle
)
187 EVT_END_SESSION(wxApp::OnEndSession
)
188 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
192 bool wxApp::Initialize()
194 // the first thing to do is to check if we're trying to run an Unicode
195 // program under Win9x - if so, abort right now as it has no chance to
198 if ( wxGetOsVersion() != wxWINDOWS_NT
)
200 // note that we can use MessageBoxW() as it's implemented even under
201 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
202 // used by wxLocale are not
206 _T("This program uses Unicode and requires Windows NT/2000.\nProgram aborted."),
207 _T("wxWindows Fatal Error"),
213 #endif // wxUSE_UNICODE
215 // Some people may wish to use this, but
216 // probably it shouldn't be here by default.
218 // wxRedirectIOToConsole();
221 wxBuffer
= new wxChar
[1500]; // FIXME
223 wxClassInfo::InitializeClasses();
226 wxPendingEventsLocker
= new wxCriticalSection
;
229 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
230 wxTheColourDatabase
->Initialize();
232 wxInitializeStockLists();
233 wxInitializeStockObjects();
235 #if wxUSE_WX_RESOURCES
236 wxInitializeResourceSystem();
239 wxBitmap::InitStandardHandlers();
241 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
242 InitCommonControls();
245 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
248 // for OLE, enlarge message queue to be as large as possible
250 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
254 // we need to initialize OLE library
255 if ( FAILED(::OleInitialize(NULL
)) )
256 wxLogError(_("Cannot initialize OLE"));
261 if (!Ctl3dRegister(wxhInstance
))
262 wxLogError(wxT("Cannot register CTL3D"));
264 Ctl3dAutoSubclass(wxhInstance
);
265 #endif // wxUSE_CTL3D
267 // VZ: these icons are not in wx.rc anyhow (but should they?)!
269 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
270 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
271 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
273 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
274 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
275 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
278 RegisterWindowClasses();
280 #ifndef __WXMICROWIN__
281 // Create the brush for disabling bitmap buttons
284 lb
.lbStyle
= BS_PATTERN
;
285 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
288 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
289 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
291 //else: wxWindows resources are probably not linked in
298 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
300 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
301 // PLEASE DO NOT ALTER THIS.
302 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
303 extern char wxDummyChar
;
304 if (wxDummyChar
) wxDummyChar
++;
307 #ifndef __WXMICROWIN__
308 wxSetKeyboardHook(TRUE
);
311 wxModule::RegisterModules();
312 if (!wxModule::InitializeModules())
317 // ---------------------------------------------------------------------------
318 // RegisterWindowClasses
319 // ---------------------------------------------------------------------------
321 // TODO we should only register classes really used by the app. For this it
322 // would be enough to just delay the class registration until an attempt
323 // to create a window of this class is made.
324 bool wxApp::RegisterWindowClasses()
328 // for each class we register one with CS_(V|H)REDRAW style and one
329 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
330 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
331 static const long styleNoRedraw
= CS_DBLCLKS
;
333 // the fields which are common to all classes
334 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
335 wndclass
.cbClsExtra
= 0;
336 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
337 wndclass
.hInstance
= wxhInstance
;
338 wndclass
.hIcon
= (HICON
) NULL
;
339 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
340 wndclass
.lpszMenuName
= NULL
;
342 // Register the frame window class.
343 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
344 wndclass
.lpszClassName
= wxFrameClassName
;
345 wndclass
.style
= styleNormal
;
347 if ( !RegisterClass(&wndclass
) )
349 wxLogLastError(wxT("RegisterClass(frame)"));
355 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
356 wndclass
.style
= styleNoRedraw
;
358 if ( !RegisterClass(&wndclass
) )
360 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
365 // Register the MDI frame window class.
366 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
367 wndclass
.lpszClassName
= wxMDIFrameClassName
;
368 wndclass
.style
= styleNormal
;
370 if ( !RegisterClass(&wndclass
) )
372 wxLogLastError(wxT("RegisterClass(MDI parent)"));
377 // "no redraw" MDI frame
378 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
379 wndclass
.style
= styleNoRedraw
;
381 if ( !RegisterClass(&wndclass
) )
383 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
388 // Register the MDI child frame window class.
389 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
390 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
391 wndclass
.style
= styleNormal
;
393 if ( !RegisterClass(&wndclass
) )
395 wxLogLastError(wxT("RegisterClass(MDI child)"));
400 // "no redraw" MDI child frame
401 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
402 wndclass
.style
= styleNoRedraw
;
404 if ( !RegisterClass(&wndclass
) )
406 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
411 // Register the panel window class.
412 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
413 wndclass
.lpszClassName
= wxPanelClassName
;
414 wndclass
.style
= styleNormal
;
416 if ( !RegisterClass(&wndclass
) )
418 wxLogLastError(wxT("RegisterClass(panel)"));
423 // Register the no redraw panel window class.
424 wndclass
.lpszClassName
= wxPanelClassNameNR
;
425 wndclass
.style
= styleNoRedraw
;
427 if ( !RegisterClass(&wndclass
) )
429 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
434 // Register the canvas and textsubwindow class name
435 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
436 wndclass
.lpszClassName
= wxCanvasClassName
;
438 if ( !RegisterClass(&wndclass
) )
440 wxLogLastError(wxT("RegisterClass(canvas)"));
445 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
446 wndclass
.style
= styleNoRedraw
;
447 if ( !RegisterClass(&wndclass
) )
449 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
457 // ---------------------------------------------------------------------------
458 // Convert Windows to argc, argv style
459 // ---------------------------------------------------------------------------
461 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
465 wxString
cmdLine(lpCmdLine
);
468 // Get application name
469 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
470 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
475 wxStrcpy(name
, wxFileNameFromPath(name
));
476 wxStripExtension(name
);
477 wxTheApp
->SetAppName(name
);
480 // Treat strings enclosed in double-quotes as single arguments
482 int len
= cmdLine
.Length();
486 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
491 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
495 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
498 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
504 i
++; // Skip past 2nd quote
506 else // Unquoted argument
509 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
512 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
520 wxTheApp
->argv
= new wxChar
*[count
+ 1];
521 for (i
= 0; i
< count
; i
++)
523 wxString
arg(args
[i
]);
524 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
526 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
527 wxTheApp
->argc
= count
;
530 //// Cleans up any wxWindows internal structures left lying around
532 void wxApp::CleanUp()
537 // flush the logged messages if any and install a 'safer' log target: the
538 // default one (wxLogGui) can't be used after the resources are freed just
539 // below and the user suppliedo ne might be even more unsafe (using any
540 // wxWindows GUI function is unsafe starting from now)
541 wxLog::DontCreateOnDemand();
543 // this will flush the old messages if any
544 delete wxLog::SetActiveTarget(new wxLogStderr
);
547 // One last chance for pending objects to be cleaned up
548 wxTheApp
->DeletePendingObjects();
550 wxModule::CleanUpModules();
552 #if wxUSE_WX_RESOURCES
553 wxCleanUpResourceSystem();
555 // wxDefaultResourceTable->ClearTable();
558 wxDeleteStockObjects();
560 // Destroy all GDI lists, etc.
561 wxDeleteStockLists();
563 delete wxTheColourDatabase
;
564 wxTheColourDatabase
= NULL
;
566 wxBitmap::CleanUpHandlers();
571 //// WINDOWS-SPECIFIC CLEANUP
573 #ifndef __WXMICROWIN__
574 wxSetKeyboardHook(FALSE
);
581 if (wxSTD_FRAME_ICON
)
582 DestroyIcon(wxSTD_FRAME_ICON
);
583 if (wxSTD_MDICHILDFRAME_ICON
)
584 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
585 if (wxSTD_MDIPARENTFRAME_ICON
)
586 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
588 if (wxDEFAULT_FRAME_ICON
)
589 DestroyIcon(wxDEFAULT_FRAME_ICON
);
590 if (wxDEFAULT_MDICHILDFRAME_ICON
)
591 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
592 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
593 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
595 if ( wxDisableButtonBrush
)
596 ::DeleteObject( wxDisableButtonBrush
);
603 Ctl3dUnregister(wxhInstance
);
607 delete wxWinHandleList
;
609 // GL: I'm annoyed ... I don't know where to put this and I don't want to
610 // create a module for that as it's part of the core.
611 delete wxPendingEvents
;
614 delete wxPendingEventsLocker
;
615 // If we don't do the following, we get an apparent memory leak
617 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
618 #endif // wxUSE_VALIDATORS
619 #endif // wxUSE_THREADS
621 wxClassInfo::CleanUpClasses();
626 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
627 // At this point we want to check if there are any memory
628 // blocks that aren't part of the wxDebugContext itself,
629 // as a special case. Then when dumping we need to ignore
630 // wxDebugContext, too.
631 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
633 wxLogMessage(wxT("There were memory leaks."));
634 wxDebugContext::Dump();
635 wxDebugContext::PrintStatistics();
637 // wxDebugContext::SetStream(NULL, NULL);
641 // do it as the very last thing because everything else can log messages
642 delete wxLog::SetActiveTarget(NULL
);
646 //----------------------------------------------------------------------
647 // Entry point helpers, used by wxPython
648 //----------------------------------------------------------------------
650 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
652 return wxApp::Initialize();
655 int WXDLLEXPORT
wxEntryInitGui()
657 return wxTheApp
->OnInitGui();
660 void WXDLLEXPORT
wxEntryCleanup()
666 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
668 // temporarily disable this warning which would be generated in release builds
671 #pragma warning(disable: 4715) // not all control paths return a value
674 //----------------------------------------------------------------------
675 // Main wxWindows entry point
676 //----------------------------------------------------------------------
677 int wxEntry(WXHINSTANCE hInstance
,
678 WXHINSTANCE
WXUNUSED(hPrevInstance
),
683 // do check for memory leaks on program exit
684 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
685 // deallocated memory which may be used to simulate low-memory condition)
686 #ifndef __WXMICROWIN__
687 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
691 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
692 // This seems to be necessary since there are 'rogue'
693 // objects present at this point (perhaps global objects?)
694 // Setting a checkpoint will ignore them as far as the
695 // memory checking facility is concerned.
696 // Of course you may argue that memory allocated in globals should be
697 // checked, but this is a reasonable compromise.
698 wxDebugContext::SetCheckpoint();
702 // take everything into a try-except block to be able to call
703 // OnFatalException() if necessary
704 #if wxUSE_ON_FATAL_EXCEPTION
707 wxhInstance
= (HINSTANCE
) hInstance
;
709 if (!wxEntryStart(0,0))
712 // create the application object or ensure that one already exists
715 // The app may have declared a global application object, but we recommend
716 // the IMPLEMENT_APP macro is used instead, which sets an initializer
717 // function for delayed, dynamic app object construction.
718 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
719 wxT("No initializer - use IMPLEMENT_APP macro.") );
721 wxTheApp
= (wxApp
*) (*wxApp::GetInitializerFunction()) ();
724 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
726 // save the WinMain() parameters
727 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
728 wxTheApp
->m_nCmdShow
= nCmdShow
;
730 // We really don't want timestamps by default, because it means
731 // we can't simply double-click on the error message and get to that
732 // line in the source. So VC++ at least, let's have a sensible default.
734 wxLog::SetTimestamp(NULL
);
739 // it is common to create a modal dialog in OnInit() (to ask/notify the
740 // user about something) but it wouldn't work if we don't change the
741 // "exit on delete last frame" flag here as when this dialog is
742 // deleted, the app would terminate (it was the last top level window
743 // as the main frame wasn't created yet!), so disable this behaviour
745 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
746 wxTheApp
->SetExitOnFrameDelete(FALSE
);
749 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
751 // restore the old flag value
752 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
759 retValue
= wxTheApp
->OnRun();
763 // we want to initialize, but not run or exit immediately.
767 //else: app initialization failed, so we skipped OnRun()
769 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
772 // Forcibly delete the window.
773 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
774 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
776 topWindow
->Close(TRUE
);
777 wxTheApp
->DeletePendingObjects();
782 wxTheApp
->SetTopWindow(NULL
);
792 #if wxUSE_ON_FATAL_EXCEPTION
794 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
795 : EXCEPTION_CONTINUE_SEARCH
) {
798 // give the user a chance to do something special about this
799 wxTheApp
->OnFatalException();
802 ::ExitProcess(3); // the same exit code as abort()
806 #endif // wxUSE_ON_FATAL_EXCEPTION
809 // restore warning state
811 #pragma warning(default: 4715) // not all control paths return a value
816 //----------------------------------------------------------------------
817 // Entry point for wxWindows + the App in a DLL
818 //----------------------------------------------------------------------
820 int wxEntry(WXHINSTANCE hInstance
)
822 wxhInstance
= (HINSTANCE
) hInstance
;
825 // The app may have declared a global application object, but we recommend
826 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
827 // for delayed, dynamic app object construction.
830 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
831 "No initializer - use IMPLEMENT_APP macro." );
833 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
836 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
839 wxTheApp
->argv
= NULL
;
845 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
846 if ( topWindow
&& topWindow
->GetHWND())
848 topWindow
->Show(TRUE
);
855 //// Static member initialization
857 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
863 m_printMode
= wxPRINT_WINDOWS
;
869 // Delete command-line args
871 for (i
= 0; i
< argc
; i
++)
878 bool wxApp::Initialized()
885 #else // Assume initialized if DLL (no way of telling)
891 * Get and process a message, returning FALSE if WM_QUIT
892 * received (and also set the flag telling the app to exit the main loop)
895 bool wxApp::DoMessage()
897 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
907 // should never happen, but let's test for it nevertheless
908 wxLogLastError(wxT("GetMessage"));
913 wxASSERT_MSG( wxThread::IsMain(),
914 wxT("only the main thread can process Windows messages") );
916 static bool s_hadGuiLock
= TRUE
;
917 static wxMsgArray s_aSavedMessages
;
919 // if a secondary thread owns is doing GUI calls, save all messages for
920 // later processing - we can't process them right now because it will
921 // lead to recursive library calls (and we're not reentrant)
922 if ( !wxGuiOwnedByMainThread() )
924 s_hadGuiLock
= FALSE
;
926 // leave out WM_COMMAND messages: too dangerous, sometimes
927 // the message will be processed twice
928 if ( !wxIsWaitingForThread() ||
929 s_currentMsg
.message
!= WM_COMMAND
)
931 s_aSavedMessages
.Add(s_currentMsg
);
938 // have we just regained the GUI lock? if so, post all of the saved
941 // FIXME of course, it's not _exactly_ the same as processing the
942 // messages normally - expect some things to break...
947 size_t count
= s_aSavedMessages
.Count();
948 for ( size_t n
= 0; n
< count
; n
++ )
950 MSG
& msg
= s_aSavedMessages
[n
];
952 if ( !ProcessMessage((WXMSG
*)&msg
) )
954 ::TranslateMessage(&msg
);
955 ::DispatchMessage(&msg
);
959 s_aSavedMessages
.Empty();
962 #endif // wxUSE_THREADS
964 // Process the message
965 DoMessage((WXMSG
*)&s_currentMsg
);
971 void wxApp::DoMessage(WXMSG
*pMsg
)
973 if ( !ProcessMessage(pMsg
) )
975 ::TranslateMessage((MSG
*)pMsg
);
976 ::DispatchMessage((MSG
*)pMsg
);
981 * Keep trying to process messages until WM_QUIT
984 * If there are messages to be processed, they will all be
985 * processed and OnIdle will not be called.
986 * When there are no more messages, OnIdle is called.
987 * If OnIdle requests more time,
988 * it will be repeatedly called so long as there are no pending messages.
989 * A 'feature' of this is that once OnIdle has decided that no more processing
990 * is required, then it won't get processing time until further messages
991 * are processed (it'll sit in DoMessage).
994 int wxApp::MainLoop()
998 while ( m_keepGoing
)
1001 wxMutexGuiLeaveOrEnter();
1002 #endif // wxUSE_THREADS
1004 while ( !Pending() && ProcessIdle() )
1007 // a message came or no more idle processing to do
1011 return s_currentMsg
.wParam
;
1014 // Returns TRUE if more time is needed.
1015 bool wxApp::ProcessIdle()
1018 event
.SetEventObject(this);
1019 ProcessEvent(event
);
1021 return event
.MoreRequested();
1024 void wxApp::ExitMainLoop()
1026 // VZ: why not ::PostQuitMessage()?
1027 m_keepGoing
= FALSE
;
1030 bool wxApp::Pending()
1032 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1035 void wxApp::Dispatch()
1041 * Give all windows a chance to preprocess
1042 * the message. Some may have accelerator tables, or have
1043 * MDI complications.
1046 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1048 MSG
*msg
= (MSG
*)wxmsg
;
1049 HWND hWnd
= msg
->hwnd
;
1050 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hWnd
);
1053 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1054 // popup the tooltip bubbles
1055 if ( wndThis
&& (msg
->message
== WM_MOUSEMOVE
) )
1057 wxToolTip
*tt
= wndThis
->GetToolTip();
1060 tt
->RelayEvent(wxmsg
);
1063 #endif // wxUSE_TOOLTIPS
1065 // Try translations first; find the youngest window with
1066 // a translation table.
1069 bool pastTopLevelWindow
= FALSE
;
1070 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1072 if ( !pastTopLevelWindow
&& wnd
->MSWTranslateMessage(wxmsg
))
1074 if ( wnd
->MSWProcessMessage(wxmsg
) )
1077 // stop at first top level window, i.e. don't try to process the key
1078 // strokes originating in a dialog using the accelerators of the parent
1079 // frame - this doesn't make much sense
1080 if ( wnd
->IsTopLevel() )
1081 pastTopLevelWindow
= TRUE
;
1087 void wxApp::OnIdle(wxIdleEvent
& event
)
1089 static bool s_inOnIdle
= FALSE
;
1091 // Avoid recursion (via ProcessEvent default case)
1097 // If there are pending events, we must process them: pending events
1098 // are either events to the threads other than main or events posted
1099 // with wxPostEvent() functions
1100 // GRG: I have moved this here so that all pending events are processed
1101 // before starting to delete any objects. This behaves better (in
1102 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1103 // behaviour. Changed Feb/2000 before 2.1.14
1104 ProcessPendingEvents();
1106 // 'Garbage' collection of windows deleted with Close().
1107 DeletePendingObjects();
1110 // flush the logged messages if any
1111 wxLog::FlushActive();
1114 // Send OnIdle events to all windows
1115 if ( SendIdleEvents() )
1117 // SendIdleEvents() returns TRUE if at least one window requested more
1119 event
.RequestMore(TRUE
);
1125 // Send idle event to all top-level windows
1126 bool wxApp::SendIdleEvents()
1128 bool needMore
= FALSE
;
1130 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1133 wxWindow
* win
= node
->GetData();
1134 if (SendIdleEvents(win
))
1136 node
= node
->GetNext();
1142 // Send idle event to window and all subwindows
1143 bool wxApp::SendIdleEvents(wxWindow
* win
)
1145 bool needMore
= FALSE
;
1148 event
.SetEventObject(win
);
1149 win
->GetEventHandler()->ProcessEvent(event
);
1151 if (event
.MoreRequested())
1154 wxNode
* node
= win
->GetChildren().First();
1157 wxWindow
* win
= (wxWindow
*) node
->Data();
1158 if (SendIdleEvents(win
))
1161 node
= node
->Next();
1166 void wxApp::DeletePendingObjects()
1168 wxNode
*node
= wxPendingDelete
.First();
1171 wxObject
*obj
= (wxObject
*)node
->Data();
1175 if (wxPendingDelete
.Member(obj
))
1178 // Deleting one object may have deleted other pending
1179 // objects, so start from beginning of list again.
1180 node
= wxPendingDelete
.First();
1184 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1187 GetTopWindow()->Close(TRUE
);
1190 // Default behaviour: close the application with prompts. The
1191 // user can veto the close, and therefore the end session.
1192 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1196 if (!GetTopWindow()->Close(!event
.CanVeto()))
1202 int wxApp::GetComCtl32Version()
1204 #ifdef __WXMICROWIN__
1208 static int s_verComCtl32
= -1;
1210 wxCRIT_SECT_DECLARE(csComCtl32
);
1211 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1213 if ( s_verComCtl32
== -1 )
1215 // initally assume no comctl32.dll at all
1219 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1221 // if so, then we can check for the version
1222 if ( hModuleComCtl32
)
1224 // try to use DllGetVersion() if available in _headers_
1225 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1226 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1227 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1228 if ( pfnDllGetVersion
)
1231 dvi
.cbSize
= sizeof(dvi
);
1233 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1236 wxLogApiError(_T("DllGetVersion"), hr
);
1240 // this is incompatible with _WIN32_IE values, but
1241 // compatible with the other values returned by
1242 // GetComCtl32Version()
1243 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1248 // DllGetVersion() unavailable either during compile or
1249 // run-time, try to guess the version otherwise
1250 if ( !s_verComCtl32
)
1252 // InitCommonControlsEx is unique to 4.70 and later
1253 FARPROC theProc
= ::GetProcAddress
1256 "InitCommonControlsEx"
1261 // not found, must be 4.00
1262 s_verComCtl32
= 400;
1266 // many symbols appeared in comctl32 4.71, could use
1267 // any of them except may be DllInstall
1268 theProc
= ::GetProcAddress
1275 // not found, must be 4.70
1276 s_verComCtl32
= 470;
1280 // found, must be 4.71
1281 s_verComCtl32
= 471;
1288 return s_verComCtl32
;
1294 wxLogError(_("Fatal error: exiting"));
1300 // Yield to incoming messages
1302 static bool gs_inYield
= FALSE
;
1306 // disable log flushing from here because a call to wxYield() shouldn't
1307 // normally result in message boxes popping up &c
1312 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1317 // we don't want to process WM_QUIT from here - it should be processed in
1318 // the main event loop in order to stop it
1320 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1321 msg
.message
!= WM_QUIT
)
1324 wxMutexGuiLeaveOrEnter();
1325 #endif // wxUSE_THREADS
1327 if ( !wxTheApp
->DoMessage() )
1331 // If they are pending events, we must process them.
1333 wxTheApp
->ProcessPendingEvents();
1335 // let the logs be flashed again
1343 // Yield to incoming messages; but fail silently if recursion is detected.
1344 bool wxYieldIfNeeded()
1352 bool wxHandleFatalExceptions(bool doit
)
1354 #if wxUSE_ON_FATAL_EXCEPTION
1355 // assume this can only be called from the main thread
1356 gs_handleExceptions
= doit
;
1360 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to sue this function"));
1367 //-----------------------------------------------------------------------------
1369 //-----------------------------------------------------------------------------
1373 // Send the top window a dummy message so idle handler processing will
1374 // start up again. Doing it this way ensures that the idle handler
1375 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1376 // the same for the main app thread only)
1377 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1380 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1382 // should never happen
1383 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1388 //-----------------------------------------------------------------------------
1391 wxApp::GetStdIcon(int which
) const
1395 case wxICON_INFORMATION
:
1396 return wxIcon("wxICON_INFO");
1398 case wxICON_QUESTION
:
1399 return wxIcon("wxICON_QUESTION");
1401 case wxICON_EXCLAMATION
:
1402 return wxIcon("wxICON_WARNING");
1405 wxFAIL_MSG(wxT("requested non existent standard icon"));
1406 // still fall through
1409 return wxIcon("wxICON_ERROR");
1413 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1414 // if in a separate file. So include it here to ensure it's linked.
1415 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))