1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/app.cpp
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
23 #if defined(__BORLANDC__)
28 #include "wx/msw/wrapcctl.h"
29 #include "wx/dynarray.h"
33 #include "wx/gdicmn.h"
36 #include "wx/cursor.h"
38 #include "wx/palette.h"
40 #include "wx/dialog.h"
41 #include "wx/msgdlg.h"
43 #include "wx/wxchar.h"
45 #include "wx/module.h"
48 #include "wx/apptrait.h"
49 #include "wx/filename.h"
50 #include "wx/dynlib.h"
51 #include "wx/evtloop.h"
53 #include "wx/msw/private.h"
54 #include "wx/msw/ole/oleutils.h"
55 #include "wx/msw/private/timer.h"
58 #include "wx/tooltip.h"
59 #endif // wxUSE_TOOLTIPS
61 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
62 // compilers don't support it (missing headers, libs, ...)
63 #if defined(__GNUWIN32_OLD__) || defined(__SYMANTEC__) || defined(__SALFORDC__)
67 #endif // broken compilers
69 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
81 #include "wx/msw/missing.h"
83 // instead of including <shlwapi.h> which is not part of the core SDK and not
84 // shipped at all with other compilers, we always define the parts of it we
85 // need here ourselves
87 // NB: DLLVER_PLATFORM_WINDOWS will be defined if shlwapi.h had been somehow
89 #ifndef DLLVER_PLATFORM_WINDOWS
90 // hopefully we don't need to change packing as DWORDs should be already
95 DWORD dwMajorVersion
; // Major version
96 DWORD dwMinorVersion
; // Minor version
97 DWORD dwBuildNumber
; // Build number
98 DWORD dwPlatformID
; // DLLVER_PLATFORM_*
101 typedef HRESULT (CALLBACK
* DLLGETVERSIONPROC
)(DLLVERSIONINFO
*);
102 #endif // defined(DLLVERSIONINFO)
105 // ---------------------------------------------------------------------------
107 // ---------------------------------------------------------------------------
109 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
110 extern void wxSetKeyboardHook(bool doIt
);
113 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
114 // with NR suffix - wxWindow::MSWCreate() supposes this
116 WXDLLIMPEXP_CORE wxChar
*wxCanvasClassName
;
117 WXDLLIMPEXP_CORE wxChar
*wxCanvasClassNameNR
;
119 WXDLLIMPEXP_CORE
const wxChar
*wxCanvasClassName
= wxT("wxWindowClass");
120 WXDLLIMPEXP_CORE
const wxChar
*wxCanvasClassNameNR
= wxT("wxWindowClassNR");
122 WXDLLIMPEXP_CORE
const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
123 WXDLLIMPEXP_CORE
const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
124 WXDLLIMPEXP_CORE
const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
125 WXDLLIMPEXP_CORE
const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
133 // ===========================================================================
134 // wxGUIAppTraits implementation
135 // ===========================================================================
137 // private class which we use to pass parameters from BeforeChildWaitLoop() to
138 // AfterChildWaitLoop()
139 struct ChildWaitLoopData
141 ChildWaitLoopData(wxWindowDisabler
*wd_
, wxWindow
*winActive_
)
144 winActive
= winActive_
;
147 wxWindowDisabler
*wd
;
151 void *wxGUIAppTraits::BeforeChildWaitLoop()
154 We use a dirty hack here to disable all application windows (which we
155 must do because otherwise the calls to wxYield() could lead to some very
156 unexpected reentrancies in the users code) but to avoid losing
157 focus/activation entirely when the child process terminates which would
158 happen if we simply disabled everything using wxWindowDisabler. Indeed,
159 remember that Windows will never activate a disabled window and when the
160 last childs window is closed and Windows looks for a window to activate
161 all our windows are still disabled. There is no way to enable them in
162 time because we don't know when the childs windows are going to be
163 closed, so the solution we use here is to keep one special tiny frame
164 enabled all the time. Then when the child terminates it will get
165 activated and when we close it below -- after reenabling all the other
166 windows! -- the previously active window becomes activated again and
171 // first disable all existing windows
172 wxWindowDisabler
*wd
= new wxWindowDisabler
;
174 // then create an "invisible" frame: it has minimal size, is positioned
175 // (hopefully) outside the screen and doesn't appear on the taskbar
176 wxWindow
*winActive
= new wxFrame
178 wxTheApp
->GetTopWindow(),
181 wxPoint(32600, 32600),
183 wxDEFAULT_FRAME_STYLE
| wxFRAME_NO_TASKBAR
187 return new ChildWaitLoopData(wd
, winActive
);
190 void wxGUIAppTraits::AlwaysYield()
195 void wxGUIAppTraits::AfterChildWaitLoop(void *dataOrig
)
199 ChildWaitLoopData
* const data
= (ChildWaitLoopData
*)dataOrig
;
203 // finally delete the dummy frame and, as wd has been already destroyed and
204 // the other windows reenabled, the activation is going to return to the
205 // window which had had it before
206 data
->winActive
->Destroy();
208 // also delete the temporary data object itself
212 bool wxGUIAppTraits::DoMessageFromThreadWait()
214 // we should return false only if the app should exit, i.e. only if
215 // Dispatch() determines that the main event loop should terminate
216 wxEventLoop
*evtLoop
= wxEventLoop::GetActive();
217 if ( !evtLoop
|| !evtLoop
->Pending() )
219 // no events means no quit event
223 return evtLoop
->Dispatch();
226 DWORD
wxGUIAppTraits::WaitForThread(WXHANDLE hThread
)
228 // if we don't have a running event loop, we shouldn't wait for the
229 // messages as we never remove them from the message queue and so we enter
230 // an infinite loop as MsgWaitForMultipleObjects() keeps returning
232 if ( !wxEventLoop::GetActive() )
233 return DoSimpleWaitForThread(hThread
);
235 return ::MsgWaitForMultipleObjects
237 1, // number of objects to wait for
238 (HANDLE
*)&hThread
, // the objects
239 false, // wait for any objects, not all
240 INFINITE
, // no timeout
241 QS_ALLINPUT
| // return as soon as there are any events
246 wxPortId
wxGUIAppTraits::GetToolkitVersion(int *majVer
, int *minVer
) const
251 // on Windows, the toolkit version is the same of the OS version
252 // as Windows integrates the OS kernel with the GUI toolkit.
253 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
254 if ( ::GetVersionEx(&info
) )
257 *majVer
= info
.dwMajorVersion
;
259 *minVer
= info
.dwMinorVersion
;
262 #if defined(__WXHANDHELD__) || defined(__WXWINCE__)
270 wxGUIAppTraits::CreateTimerImpl(wxTimer
*timer
)
272 return new wxMSWTimerImpl(timer
);
275 // ===========================================================================
276 // wxApp implementation
277 // ===========================================================================
279 int wxApp::m_nCmdShow
= SW_SHOWNORMAL
;
281 // ---------------------------------------------------------------------------
283 // ---------------------------------------------------------------------------
285 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
287 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
288 EVT_IDLE(wxApp::OnIdle
)
289 EVT_END_SESSION(wxApp::OnEndSession
)
290 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
293 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
295 class wxCallBaseCleanup
298 wxCallBaseCleanup(wxApp
*app
) : m_app(app
) { }
299 ~wxCallBaseCleanup() { if ( m_app
) m_app
->wxAppBase::CleanUp(); }
301 void Dismiss() { m_app
= NULL
; }
308 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
310 if ( !wxAppBase::Initialize(argc
, argv
) )
313 // ensure that base cleanup is done if we return too early
314 wxCallBaseCleanup
callBaseCleanup(this);
317 wxString tmp
= GetAppName();
318 tmp
+= wxT("ClassName");
319 wxCanvasClassName
= wxStrdup( tmp
.c_str() );
321 wxCanvasClassNameNR
= wxStrdup( tmp
.c_str() );
322 HWND hWnd
= FindWindow( wxCanvasClassNameNR
, NULL
);
325 SetForegroundWindow( (HWND
)(((DWORD
)hWnd
)|0x01) );
330 #if !defined(__WXMICROWIN__)
331 InitCommonControls();
332 #endif // !defined(__WXMICROWIN__)
334 #if defined(__SMARTPHONE__) || defined(__POCKETPC__)
335 SHInitExtraControls();
339 // Don't show a message box if a function such as SHGetFileInfo
340 // fails to find a device.
341 SetErrorMode(SEM_FAILCRITICALERRORS
|SEM_NOOPENFILEERRORBOX
);
346 RegisterWindowClasses();
348 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
350 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
351 wxSetKeyboardHook(true);
354 callBaseCleanup
.Dismiss();
359 // ---------------------------------------------------------------------------
360 // RegisterWindowClasses
361 // ---------------------------------------------------------------------------
363 // TODO we should only register classes really used by the app. For this it
364 // would be enough to just delay the class registration until an attempt
365 // to create a window of this class is made.
366 bool wxApp::RegisterWindowClasses()
369 wxZeroMemory(wndclass
);
371 // for each class we register one with CS_(V|H)REDRAW style and one
372 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
373 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
374 static const long styleNoRedraw
= CS_DBLCLKS
;
376 // the fields which are common to all classes
377 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
378 wndclass
.hInstance
= wxhInstance
;
379 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
381 // register the class for all normal windows
382 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_BTNFACE
+ 1);
383 wndclass
.lpszClassName
= wxCanvasClassName
;
384 wndclass
.style
= styleNormal
;
386 if ( !RegisterClass(&wndclass
) )
388 wxLogLastError(wxT("RegisterClass(frame)"));
392 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
393 wndclass
.style
= styleNoRedraw
;
395 if ( !RegisterClass(&wndclass
) )
397 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
400 // Register the MDI frame window class.
401 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
402 wndclass
.lpszClassName
= wxMDIFrameClassName
;
403 wndclass
.style
= styleNormal
;
405 if ( !RegisterClass(&wndclass
) )
407 wxLogLastError(wxT("RegisterClass(MDI parent)"));
410 // "no redraw" MDI frame
411 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
412 wndclass
.style
= styleNoRedraw
;
414 if ( !RegisterClass(&wndclass
) )
416 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
419 // Register the MDI child frame window class.
420 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
421 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
422 wndclass
.style
= styleNormal
;
424 if ( !RegisterClass(&wndclass
) )
426 wxLogLastError(wxT("RegisterClass(MDI child)"));
429 // "no redraw" MDI child frame
430 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
431 wndclass
.style
= styleNoRedraw
;
433 if ( !RegisterClass(&wndclass
) )
435 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
441 // ---------------------------------------------------------------------------
442 // UnregisterWindowClasses
443 // ---------------------------------------------------------------------------
445 bool wxApp::UnregisterWindowClasses()
449 #ifndef __WXMICROWIN__
450 // MDI frame window class.
451 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
453 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
458 // "no redraw" MDI frame
459 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
461 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
466 // MDI child frame window class.
467 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
469 wxLogLastError(wxT("UnregisterClass(MDI child)"));
474 // "no redraw" MDI child frame
475 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
477 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
483 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
485 wxLogLastError(wxT("UnregisterClass(canvas)"));
490 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
492 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
496 #endif // __WXMICROWIN__
501 void wxApp::CleanUp()
503 // all objects pending for deletion must be deleted first, otherwise we
504 // would crash when they use wxWinHandleHash (and UnregisterWindowClasses()
505 // call wouldn't succeed as long as any windows still exist), so call the
506 // base class method first and only then do our clean up
507 wxAppBase::CleanUp();
509 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
510 wxSetKeyboardHook(false);
515 // for an EXE the classes are unregistered when it terminates but DLL may
516 // be loaded several times (load/unload/load) into the same process in
517 // which case the registration will fail after the first time if we don't
518 // unregister the classes now
519 UnregisterWindowClasses();
521 delete wxWinHandleHash
;
522 wxWinHandleHash
= NULL
;
525 free( wxCanvasClassName
);
526 free( wxCanvasClassNameNR
);
530 // ----------------------------------------------------------------------------
532 // ----------------------------------------------------------------------------
536 m_printMode
= wxPRINT_WINDOWS
;
543 // ----------------------------------------------------------------------------
544 // wxApp idle handling
545 // ----------------------------------------------------------------------------
547 void wxApp::OnIdle(wxIdleEvent
& event
)
549 wxAppBase::OnIdle(event
);
551 #if wxUSE_DC_CACHEING
552 // automated DC cache management: clear the cached DCs and bitmap
553 // if it's likely that the app has finished with them, that is, we
554 // get an idle event and we're not dragging anything.
555 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
557 #endif // wxUSE_DC_CACHEING
560 void wxApp::WakeUpIdle()
562 // Send the top window a dummy message so idle handler processing will
563 // start up again. Doing it this way ensures that the idle handler
564 // wakes up in the right thread (see also wxWakeUpMainThread() which does
565 // the same for the main app thread only)
566 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
569 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
571 // should never happen
572 wxLogLastError(wxT("PostMessage(WM_NULL)"));
577 // ----------------------------------------------------------------------------
578 // other wxApp event hanlders
579 // ----------------------------------------------------------------------------
581 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
584 GetTopWindow()->Close(true);
587 // Default behaviour: close the application with prompts. The
588 // user can veto the close, and therefore the end session.
589 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
593 if (!GetTopWindow()->Close(!event
.CanVeto()))
598 // ----------------------------------------------------------------------------
600 // ----------------------------------------------------------------------------
603 int wxApp::GetComCtl32Version()
605 #if defined(__WXMICROWIN__) || defined(__WXWINCE__)
610 // NB: this is MT-ok as in the worst case we'd compute s_verComCtl32 twice,
611 // but as its value should be the same both times it doesn't matter
612 static int s_verComCtl32
= -1;
614 if ( s_verComCtl32
== -1 )
616 // initally assume no comctl32.dll at all
619 // we're prepared to handle the errors
622 #if wxUSE_DYNLIB_CLASS
624 wxDynamicLibrary
dllComCtl32(_T("comctl32.dll"), wxDL_VERBATIM
);
626 // if so, then we can check for the version
627 if ( dllComCtl32
.IsLoaded() )
629 // now check if the function is available during run-time
630 wxDYNLIB_FUNCTION( DLLGETVERSIONPROC
, DllGetVersion
, dllComCtl32
);
631 if ( pfnDllGetVersion
)
634 dvi
.cbSize
= sizeof(dvi
);
636 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
639 wxLogApiError(_T("DllGetVersion"), hr
);
643 // this is incompatible with _WIN32_IE values, but
644 // compatible with the other values returned by
645 // GetComCtl32Version()
646 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
651 // if DllGetVersion() is unavailable either during compile or
652 // run-time, try to guess the version otherwise
653 if ( !s_verComCtl32
)
655 // InitCommonControlsEx is unique to 4.70 and later
656 void *pfn
= dllComCtl32
.GetSymbol(_T("InitCommonControlsEx"));
659 // not found, must be 4.00
664 // many symbols appeared in comctl32 4.71, could use any of
665 // them except may be DllInstall()
666 pfn
= dllComCtl32
.GetSymbol(_T("InitializeFlatSB"));
669 // not found, must be 4.70
674 // found, must be 4.71 or later
683 return s_verComCtl32
;
684 #endif // Microwin/!Microwin
687 // Yield to incoming messages
689 bool wxApp::Yield(bool onlyIfNeeded
)
692 static bool s_inYield
= false;
695 // disable log flushing from here because a call to wxYield() shouldn't
696 // normally result in message boxes popping up &c
704 wxFAIL_MSG( wxT("wxYield called recursively" ) );
712 // we don't want to process WM_QUIT from here - it should be processed in
713 // the main event loop in order to stop it
715 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
716 msg
.message
!= WM_QUIT
)
719 wxMutexGuiLeaveOrEnter();
720 #endif // wxUSE_THREADS
722 if ( !wxTheApp
->Dispatch() )
726 // if there are pending events, we must process them.
727 ProcessPendingEvents();
730 // let the logs be flashed again
741 // ----------------------------------------------------------------------------
742 // exception handling
743 // ----------------------------------------------------------------------------
745 bool wxApp::OnExceptionInMainLoop()
747 // ask the user about what to do: use the Win32 API function here as it
748 // could be dangerous to use any wxWidgets code in this state
753 _T("An unhandled exception occurred. Press \"Abort\" to \
754 terminate the program,\r\n\
755 \"Retry\" to exit the program normally and \"Ignore\" to try to continue."),
756 _T("Unhandled exception"),
757 MB_ABORTRETRYIGNORE
|
767 wxFAIL_MSG( _T("unexpected MessageBox() return code") );
778 #endif // wxUSE_EXCEPTIONS