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(__CYGWIN10__))
93 #include "wx/msw/msvcrt.h"
95 // ----------------------------------------------------------------------------
96 // conditional compilation
97 // ----------------------------------------------------------------------------
99 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
100 // defined before) and shows us what common control features are available
101 // during the compile time (it doesn't mean that they will be available during
102 // the run-time, use GetComCtl32Version() to test for them!). The possible
105 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
106 // 0x0300 4.70 IE 3.x
107 // 0x0400 4.71 IE 4.0
108 // 0x0401 4.72 IE 4.01 and Win98
109 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
112 // minimal set of features by default
113 #define _WIN32_IE 0x0200
116 #if _WIN32_IE >= 0x0300
120 // ---------------------------------------------------------------------------
122 // ---------------------------------------------------------------------------
124 extern wxChar
*wxBuffer
;
125 extern wxList
*wxWinHandleList
;
126 extern wxList WXDLLEXPORT wxPendingDelete
;
127 extern void wxSetKeyboardHook(bool doIt
);
130 wxApp
*wxTheApp
= NULL
;
132 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
133 // with NR suffix - wxWindow::MSWCreate() supposes this
134 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
135 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
136 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
137 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
138 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
139 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
140 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
141 const wxChar
*wxPanelClassNameNR
= wxT("wxPanelClassNR");
142 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
143 const wxChar
*wxCanvasClassNameNR
= wxT("wxCanvasClassNR");
145 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
146 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
147 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
149 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
150 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
151 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
153 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
155 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
157 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
158 // needs compiler support for Win32 SEH. Others (especially Borland)
159 // probably have it too, but I'm not sure about how it works
160 // JACS: get 'Cannot use __try in functions that require unwinding
161 // in Unicode mode, so disabling.
162 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
163 #undef wxUSE_ON_FATAL_EXCEPTION
164 #define wxUSE_ON_FATAL_EXCEPTION 0
167 #if wxUSE_ON_FATAL_EXCEPTION
168 static bool gs_handleExceptions
= FALSE
;
171 // ===========================================================================
173 // ===========================================================================
175 // ---------------------------------------------------------------------------
177 // ---------------------------------------------------------------------------
179 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
181 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
182 EVT_IDLE(wxApp::OnIdle
)
183 EVT_END_SESSION(wxApp::OnEndSession
)
184 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
188 bool wxApp::Initialize()
190 // the first thing to do is to check if we're trying to run an Unicode
191 // program under Win9x - if so, abort right now as it has no chance to
194 if ( wxGetOsVersion() != wxWINDOWS_NT
)
196 // note that we can use MessageBoxW() as it's implemented even under
197 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
198 // used by wxLocale are not
202 _T("This program uses Unicode and requires Windows NT/2000.\nProgram aborted."),
203 _T("wxWindows Fatal Error"),
209 #endif // wxUSE_UNICODE
211 // Some people may wish to use this, but
212 // probably it shouldn't be here by default.
214 // wxRedirectIOToConsole();
217 wxBuffer
= new wxChar
[1500]; // FIXME
219 wxClassInfo::InitializeClasses();
222 wxPendingEventsLocker
= new wxCriticalSection
;
225 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
226 wxTheColourDatabase
->Initialize();
228 wxInitializeStockLists();
229 wxInitializeStockObjects();
231 #if wxUSE_WX_RESOURCES
232 wxInitializeResourceSystem();
235 wxBitmap::InitStandardHandlers();
237 #if defined(__WIN95__)
238 InitCommonControls();
242 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP || wxUSE_DATAOBJ
245 // for OLE, enlarge message queue to be as large as possible
247 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
250 // we need to initialize OLE library
251 if ( FAILED(::OleInitialize(NULL
)) )
252 wxLogError(_("Cannot initialize OLE"));
257 if (!Ctl3dRegister(wxhInstance
))
258 wxLogError(wxT("Cannot register CTL3D"));
260 Ctl3dAutoSubclass(wxhInstance
);
261 #endif // wxUSE_CTL3D
263 // VZ: these icons are not in wx.rc anyhow (but should they?)!
265 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
266 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
267 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
269 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
270 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
271 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
274 RegisterWindowClasses();
276 // Create the brush for disabling bitmap buttons
279 lb
.lbStyle
= BS_PATTERN
;
280 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
283 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
284 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
286 //else: wxWindows resources are probably not linked in
292 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
294 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
295 // PLEASE DO NOT ALTER THIS.
296 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
297 extern char wxDummyChar
;
298 if (wxDummyChar
) wxDummyChar
++;
301 wxSetKeyboardHook(TRUE
);
303 wxModule::RegisterModules();
304 if (!wxModule::InitializeModules())
309 // ---------------------------------------------------------------------------
310 // RegisterWindowClasses
311 // ---------------------------------------------------------------------------
313 // TODO we should only register classes really used by the app. For this it
314 // would be enough to just delay the class registration until an attempt
315 // to create a window of this class is made.
316 bool wxApp::RegisterWindowClasses()
320 // for each class we register one with CS_(V|H)REDRAW style and one
321 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
322 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
323 static const long styleNoRedraw
= CS_DBLCLKS
;
325 // the fields which are common to all classes
326 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
327 wndclass
.cbClsExtra
= 0;
328 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
329 wndclass
.hInstance
= wxhInstance
;
330 wndclass
.hIcon
= (HICON
) NULL
;
331 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
332 wndclass
.lpszMenuName
= NULL
;
334 // Register the frame window class.
335 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
336 wndclass
.lpszClassName
= wxFrameClassName
;
337 wndclass
.style
= styleNormal
;
339 if ( !RegisterClass(&wndclass
) )
341 wxLogLastError(wxT("RegisterClass(frame)"));
347 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
348 wndclass
.style
= styleNoRedraw
;
350 if ( !RegisterClass(&wndclass
) )
352 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
357 // Register the MDI frame window class.
358 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
359 wndclass
.lpszClassName
= wxMDIFrameClassName
;
360 wndclass
.style
= styleNormal
;
362 if ( !RegisterClass(&wndclass
) )
364 wxLogLastError(wxT("RegisterClass(MDI parent)"));
369 // "no redraw" MDI frame
370 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
371 wndclass
.style
= styleNoRedraw
;
373 if ( !RegisterClass(&wndclass
) )
375 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
380 // Register the MDI child frame window class.
381 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
382 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
383 wndclass
.style
= styleNormal
;
385 if ( !RegisterClass(&wndclass
) )
387 wxLogLastError(wxT("RegisterClass(MDI child)"));
392 // "no redraw" MDI child frame
393 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
394 wndclass
.style
= styleNoRedraw
;
396 if ( !RegisterClass(&wndclass
) )
398 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
403 // Register the panel window class.
404 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
405 wndclass
.lpszClassName
= wxPanelClassName
;
406 wndclass
.style
= styleNormal
;
408 if ( !RegisterClass(&wndclass
) )
410 wxLogLastError(wxT("RegisterClass(panel)"));
415 // Register the no redraw panel window class.
416 wndclass
.lpszClassName
= wxPanelClassNameNR
;
417 wndclass
.style
= styleNoRedraw
;
419 if ( !RegisterClass(&wndclass
) )
421 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
426 // Register the canvas and textsubwindow class name
427 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
428 wndclass
.lpszClassName
= wxCanvasClassName
;
430 if ( !RegisterClass(&wndclass
) )
432 wxLogLastError(wxT("RegisterClass(canvas)"));
437 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
438 wndclass
.style
= styleNoRedraw
;
439 if ( !RegisterClass(&wndclass
) )
441 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
449 // ---------------------------------------------------------------------------
450 // Convert Windows to argc, argv style
451 // ---------------------------------------------------------------------------
453 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
457 wxString
cmdLine(lpCmdLine
);
460 // Get application name
461 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
462 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
467 wxStrcpy(name
, wxFileNameFromPath(name
));
468 wxStripExtension(name
);
469 wxTheApp
->SetAppName(name
);
472 // Treat strings enclosed in double-quotes as single arguments
474 int len
= cmdLine
.Length();
478 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
483 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
487 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
490 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
496 i
++; // Skip past 2nd quote
498 else // Unquoted argument
501 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
504 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
512 wxTheApp
->argv
= new wxChar
*[count
+ 1];
513 for (i
= 0; i
< count
; i
++)
515 wxString
arg(args
[i
]);
516 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
518 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
519 wxTheApp
->argc
= count
;
522 //// Cleans up any wxWindows internal structures left lying around
524 void wxApp::CleanUp()
529 // flush the logged messages if any and install a 'safer' log target: the
530 // default one (wxLogGui) can't be used after the resources are freed just
531 // below and the user suppliedo ne might be even more unsafe (using any
532 // wxWindows GUI function is unsafe starting from now)
533 wxLog::DontCreateOnDemand();
535 // this will flush the old messages if any
536 delete wxLog::SetActiveTarget(new wxLogStderr
);
539 // One last chance for pending objects to be cleaned up
540 wxTheApp
->DeletePendingObjects();
542 wxModule::CleanUpModules();
544 #if wxUSE_WX_RESOURCES
545 wxCleanUpResourceSystem();
547 // wxDefaultResourceTable->ClearTable();
550 wxDeleteStockObjects();
552 // Destroy all GDI lists, etc.
553 wxDeleteStockLists();
555 delete wxTheColourDatabase
;
556 wxTheColourDatabase
= NULL
;
558 wxBitmap::CleanUpHandlers();
563 //// WINDOWS-SPECIFIC CLEANUP
565 wxSetKeyboardHook(FALSE
);
571 if (wxSTD_FRAME_ICON
)
572 DestroyIcon(wxSTD_FRAME_ICON
);
573 if (wxSTD_MDICHILDFRAME_ICON
)
574 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
575 if (wxSTD_MDIPARENTFRAME_ICON
)
576 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
578 if (wxDEFAULT_FRAME_ICON
)
579 DestroyIcon(wxDEFAULT_FRAME_ICON
);
580 if (wxDEFAULT_MDICHILDFRAME_ICON
)
581 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
582 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
583 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
585 if ( wxDisableButtonBrush
)
586 ::DeleteObject( wxDisableButtonBrush
);
593 Ctl3dUnregister(wxhInstance
);
597 delete wxWinHandleList
;
599 // GL: I'm annoyed ... I don't know where to put this and I don't want to
600 // create a module for that as it's part of the core.
601 delete wxPendingEvents
;
604 delete wxPendingEventsLocker
;
605 // If we don't do the following, we get an apparent memory leak
607 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
608 #endif // wxUSE_VALIDATORS
609 #endif // wxUSE_THREADS
611 wxClassInfo::CleanUpClasses();
616 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
617 // At this point we want to check if there are any memory
618 // blocks that aren't part of the wxDebugContext itself,
619 // as a special case. Then when dumping we need to ignore
620 // wxDebugContext, too.
621 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
623 wxLogMessage(wxT("There were memory leaks."));
624 wxDebugContext::Dump();
625 wxDebugContext::PrintStatistics();
627 // wxDebugContext::SetStream(NULL, NULL);
631 // do it as the very last thing because everything else can log messages
632 delete wxLog::SetActiveTarget(NULL
);
636 //----------------------------------------------------------------------
637 // Entry point helpers, used by wxPython
638 //----------------------------------------------------------------------
640 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
642 return wxApp::Initialize();
645 int WXDLLEXPORT
wxEntryInitGui()
647 return wxTheApp
->OnInitGui();
650 void WXDLLEXPORT
wxEntryCleanup()
656 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
658 // temporarily disable this warning which would be generated in release builds
661 #pragma warning(disable: 4715) // not all control paths return a value
664 //----------------------------------------------------------------------
665 // Main wxWindows entry point
666 //----------------------------------------------------------------------
667 int wxEntry(WXHINSTANCE hInstance
,
668 WXHINSTANCE
WXUNUSED(hPrevInstance
),
673 // do check for memory leaks on program exit
674 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
675 // deallocated memory which may be used to simulate low-memory condition)
676 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
678 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
679 // This seems to be necessary since there are 'rogue'
680 // objects present at this point (perhaps global objects?)
681 // Setting a checkpoint will ignore them as far as the
682 // memory checking facility is concerned.
683 // Of course you may argue that memory allocated in globals should be
684 // checked, but this is a reasonable compromise.
685 wxDebugContext::SetCheckpoint();
689 // take everything into a try-except block to be able to call
690 // OnFatalException() if necessary
691 #if wxUSE_ON_FATAL_EXCEPTION
694 wxhInstance
= (HINSTANCE
) hInstance
;
696 if (!wxEntryStart(0,0))
699 // create the application object or ensure that one already exists
702 // The app may have declared a global application object, but we recommend
703 // the IMPLEMENT_APP macro is used instead, which sets an initializer
704 // function for delayed, dynamic app object construction.
705 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
706 wxT("No initializer - use IMPLEMENT_APP macro.") );
708 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
711 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
713 // save the WinMain() parameters
714 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
715 wxTheApp
->m_nCmdShow
= nCmdShow
;
717 // We really don't want timestamps by default, because it means
718 // we can't simply double-click on the error message and get to that
719 // line in the source. So VC++ at least, let's have a sensible default.
721 wxLog::SetTimestamp(NULL
);
726 // it is common to create a modal dialog in OnInit() (to ask/notify the
727 // user about something) but it wouldn't work if we don't change the
728 // "exit on delete last frame" flag here as when this dialog is
729 // deleted, the app would terminate (it was the last top level window
730 // as the main frame wasn't created yet!), so disable this behaviour
732 bool exitOnLastFrameDelete
= wxTheApp
->GetExitOnFrameDelete();
733 wxTheApp
->SetExitOnFrameDelete(FALSE
);
736 retValue
= wxEntryInitGui() && wxTheApp
->OnInit() ? 0 : -1;
738 // restore the old flag value
739 wxTheApp
->SetExitOnFrameDelete(exitOnLastFrameDelete
);
746 retValue
= wxTheApp
->OnRun();
750 // we want to initialize, but not run or exit immediately.
754 //else: app initialization failed, so we skipped OnRun()
756 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
759 // Forcibly delete the window.
760 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
761 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
763 topWindow
->Close(TRUE
);
764 wxTheApp
->DeletePendingObjects();
769 wxTheApp
->SetTopWindow(NULL
);
779 #if wxUSE_ON_FATAL_EXCEPTION
781 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
782 : EXCEPTION_CONTINUE_SEARCH
) {
785 // give the user a chance to do something special about this
786 wxTheApp
->OnFatalException();
789 ::ExitProcess(3); // the same exit code as abort()
793 #endif // wxUSE_ON_FATAL_EXCEPTION
796 // restore warning state
798 #pragma warning(default: 4715) // not all control paths return a value
803 //----------------------------------------------------------------------
804 // Entry point for wxWindows + the App in a DLL
805 //----------------------------------------------------------------------
807 int wxEntry(WXHINSTANCE hInstance
)
809 wxhInstance
= (HINSTANCE
) hInstance
;
812 // The app may have declared a global application object, but we recommend
813 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
814 // for delayed, dynamic app object construction.
817 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
818 "No initializer - use IMPLEMENT_APP macro." );
820 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
823 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
826 wxTheApp
->argv
= NULL
;
832 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
833 if ( topWindow
&& topWindow
->GetHWND())
835 topWindow
->Show(TRUE
);
842 //// Static member initialization
844 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
850 m_printMode
= wxPRINT_WINDOWS
;
856 // Delete command-line args
858 for (i
= 0; i
< argc
; i
++)
865 bool wxApp::Initialized()
872 #else // Assume initialized if DLL (no way of telling)
878 * Get and process a message, returning FALSE if WM_QUIT
879 * received (and also set the flag telling the app to exit the main loop)
882 bool wxApp::DoMessage()
884 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
894 // should never happen, but let's test for it nevertheless
895 wxLogLastError(wxT("GetMessage"));
900 wxASSERT_MSG( wxThread::IsMain(),
901 wxT("only the main thread can process Windows messages") );
903 static bool s_hadGuiLock
= TRUE
;
904 static wxMsgArray s_aSavedMessages
;
906 // if a secondary thread owns is doing GUI calls, save all messages for
907 // later processing - we can't process them right now because it will
908 // lead to recursive library calls (and we're not reentrant)
909 if ( !wxGuiOwnedByMainThread() )
911 s_hadGuiLock
= FALSE
;
913 // leave out WM_COMMAND messages: too dangerous, sometimes
914 // the message will be processed twice
915 if ( !wxIsWaitingForThread() ||
916 s_currentMsg
.message
!= WM_COMMAND
)
918 s_aSavedMessages
.Add(s_currentMsg
);
925 // have we just regained the GUI lock? if so, post all of the saved
928 // FIXME of course, it's not _exactly_ the same as processing the
929 // messages normally - expect some things to break...
934 size_t count
= s_aSavedMessages
.Count();
935 for ( size_t n
= 0; n
< count
; n
++ )
937 MSG
& msg
= s_aSavedMessages
[n
];
939 if ( !ProcessMessage((WXMSG
*)&msg
) )
941 ::TranslateMessage(&msg
);
942 ::DispatchMessage(&msg
);
946 s_aSavedMessages
.Empty();
949 #endif // wxUSE_THREADS
951 // Process the message
952 DoMessage((WXMSG
*)&s_currentMsg
);
958 void wxApp::DoMessage(WXMSG
*pMsg
)
960 if ( !ProcessMessage(pMsg
) )
962 ::TranslateMessage((MSG
*)pMsg
);
963 ::DispatchMessage((MSG
*)pMsg
);
968 * Keep trying to process messages until WM_QUIT
971 * If there are messages to be processed, they will all be
972 * processed and OnIdle will not be called.
973 * When there are no more messages, OnIdle is called.
974 * If OnIdle requests more time,
975 * it will be repeatedly called so long as there are no pending messages.
976 * A 'feature' of this is that once OnIdle has decided that no more processing
977 * is required, then it won't get processing time until further messages
978 * are processed (it'll sit in DoMessage).
981 int wxApp::MainLoop()
985 while ( m_keepGoing
)
988 wxMutexGuiLeaveOrEnter();
989 #endif // wxUSE_THREADS
991 while ( !Pending() && ProcessIdle() )
994 // a message came or no more idle processing to do
998 return s_currentMsg
.wParam
;
1001 // Returns TRUE if more time is needed.
1002 bool wxApp::ProcessIdle()
1005 event
.SetEventObject(this);
1006 ProcessEvent(event
);
1008 return event
.MoreRequested();
1011 void wxApp::ExitMainLoop()
1013 // VZ: why not ::PostQuitMessage()?
1014 m_keepGoing
= FALSE
;
1017 bool wxApp::Pending()
1019 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
1022 void wxApp::Dispatch()
1028 * Give all windows a chance to preprocess
1029 * the message. Some may have accelerator tables, or have
1030 * MDI complications.
1033 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1035 MSG
*msg
= (MSG
*)wxmsg
;
1036 HWND hWnd
= msg
->hwnd
;
1037 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hWnd
);
1040 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1041 // popup the tooltip bubbles
1042 if ( wndThis
&& (msg
->message
== WM_MOUSEMOVE
) )
1044 wxToolTip
*tt
= wndThis
->GetToolTip();
1047 tt
->RelayEvent(wxmsg
);
1050 #endif // wxUSE_TOOLTIPS
1052 // Try translations first; find the youngest window with
1053 // a translation table.
1056 bool pastTopLevelWindow
= FALSE
;
1057 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1059 if ( !pastTopLevelWindow
&& wnd
->MSWTranslateMessage(wxmsg
))
1061 if ( wnd
->MSWProcessMessage(wxmsg
) )
1064 // stop at first top level window, i.e. don't try to process the key
1065 // strokes originating in a dialog using the accelerators of the parent
1066 // frame - this doesn't make much sense
1067 if ( wnd
->IsTopLevel() )
1068 pastTopLevelWindow
= TRUE
;
1074 void wxApp::OnIdle(wxIdleEvent
& event
)
1076 static bool s_inOnIdle
= FALSE
;
1078 // Avoid recursion (via ProcessEvent default case)
1084 // If there are pending events, we must process them: pending events
1085 // are either events to the threads other than main or events posted
1086 // with wxPostEvent() functions
1087 // GRG: I have moved this here so that all pending events are processed
1088 // before starting to delete any objects. This behaves better (in
1089 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1090 // behaviour. Changed Feb/2000 before 2.1.14
1091 ProcessPendingEvents();
1093 // 'Garbage' collection of windows deleted with Close().
1094 DeletePendingObjects();
1097 // flush the logged messages if any
1098 wxLog::FlushActive();
1101 // Send OnIdle events to all windows
1102 if ( SendIdleEvents() )
1104 // SendIdleEvents() returns TRUE if at least one window requested more
1106 event
.RequestMore(TRUE
);
1112 // Send idle event to all top-level windows
1113 bool wxApp::SendIdleEvents()
1115 bool needMore
= FALSE
;
1117 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1120 wxWindow
* win
= node
->GetData();
1121 if (SendIdleEvents(win
))
1123 node
= node
->GetNext();
1129 // Send idle event to window and all subwindows
1130 bool wxApp::SendIdleEvents(wxWindow
* win
)
1132 bool needMore
= FALSE
;
1135 event
.SetEventObject(win
);
1136 win
->GetEventHandler()->ProcessEvent(event
);
1138 if (event
.MoreRequested())
1141 wxNode
* node
= win
->GetChildren().First();
1144 wxWindow
* win
= (wxWindow
*) node
->Data();
1145 if (SendIdleEvents(win
))
1148 node
= node
->Next();
1153 void wxApp::DeletePendingObjects()
1155 wxNode
*node
= wxPendingDelete
.First();
1158 wxObject
*obj
= (wxObject
*)node
->Data();
1162 if (wxPendingDelete
.Member(obj
))
1165 // Deleting one object may have deleted other pending
1166 // objects, so start from beginning of list again.
1167 node
= wxPendingDelete
.First();
1171 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1174 GetTopWindow()->Close(TRUE
);
1177 // Default behaviour: close the application with prompts. The
1178 // user can veto the close, and therefore the end session.
1179 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1183 if (!GetTopWindow()->Close(!event
.CanVeto()))
1189 int wxApp::GetComCtl32Version()
1192 static int s_verComCtl32
= -1;
1194 wxCRIT_SECT_DECLARE(csComCtl32
);
1195 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1197 if ( s_verComCtl32
== -1 )
1199 // initally assume no comctl32.dll at all
1203 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1205 // if so, then we can check for the version
1206 if ( hModuleComCtl32
)
1208 // try to use DllGetVersion() if available in _headers_
1209 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1210 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1211 ::GetProcAddress(hModuleComCtl32
, "DllGetVersion");
1212 if ( pfnDllGetVersion
)
1215 dvi
.cbSize
= sizeof(dvi
);
1217 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1220 wxLogApiError(_T("DllGetVersion"), hr
);
1224 // this is incompatible with _WIN32_IE values, but
1225 // compatible with the other values returned by
1226 // GetComCtl32Version()
1227 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1232 // DllGetVersion() unavailable either during compile or
1233 // run-time, try to guess the version otherwise
1234 if ( !s_verComCtl32
)
1236 // InitCommonControlsEx is unique to 4.70 and later
1237 FARPROC theProc
= ::GetProcAddress
1240 "InitCommonControlsEx"
1245 // not found, must be 4.00
1246 s_verComCtl32
= 400;
1250 // many symbols appeared in comctl32 4.71, could use
1251 // any of them except may be DllInstall
1252 theProc
= ::GetProcAddress
1259 // not found, must be 4.70
1260 s_verComCtl32
= 470;
1264 // found, must be 4.71
1265 s_verComCtl32
= 471;
1272 return s_verComCtl32
;
1277 wxLogError(_("Fatal error: exiting"));
1283 // Yield to incoming messages
1285 static bool gs_inYield
= FALSE
;
1289 // disable log flushing from here because a call to wxYield() shouldn't
1290 // normally result in message boxes popping up &c
1295 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1300 // we don't want to process WM_QUIT from here - it should be processed in
1301 // the main event loop in order to stop it
1303 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1304 msg
.message
!= WM_QUIT
)
1307 wxMutexGuiLeaveOrEnter();
1308 #endif // wxUSE_THREADS
1310 if ( !wxTheApp
->DoMessage() )
1314 // If they are pending events, we must process them.
1316 wxTheApp
->ProcessPendingEvents();
1318 // let the logs be flashed again
1326 // Yield to incoming messages; but fail silently if recursion is detected.
1327 bool wxYieldIfNeeded()
1335 bool wxHandleFatalExceptions(bool doit
)
1337 #if wxUSE_ON_FATAL_EXCEPTION
1338 // assume this can only be called from the main thread
1339 gs_handleExceptions
= doit
;
1343 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to sue this function"));
1350 //-----------------------------------------------------------------------------
1352 //-----------------------------------------------------------------------------
1356 // Send the top window a dummy message so idle handler processing will
1357 // start up again. Doing it this way ensures that the idle handler
1358 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1359 // the same for the main app thread only)
1360 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1363 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1365 // should never happen
1366 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1371 //-----------------------------------------------------------------------------
1374 wxApp::GetStdIcon(int which
) const
1378 case wxICON_INFORMATION
:
1379 return wxIcon("wxICON_INFO");
1381 case wxICON_QUESTION
:
1382 return wxIcon("wxICON_QUESTION");
1384 case wxICON_EXCLAMATION
:
1385 return wxIcon("wxICON_WARNING");
1388 wxFAIL_MSG(wxT("requested non existent standard icon"));
1389 // still fall through
1392 return wxIcon("wxICON_ERROR");
1396 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1397 // if in a separate file. So include it here to ensure it's linked.
1398 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))