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"
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 wxEventLoopBase
* const 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__)
269 wxTimerImpl
*wxGUIAppTraits::CreateTimerImpl(wxTimer
*timer
)
271 return new wxMSWTimerImpl(timer
);
274 wxEventLoopBase
* wxGUIAppTraits::CreateEventLoop()
276 return new wxEventLoop
;
279 // ===========================================================================
280 // wxApp implementation
281 // ===========================================================================
283 int wxApp::m_nCmdShow
= SW_SHOWNORMAL
;
285 // ---------------------------------------------------------------------------
287 // ---------------------------------------------------------------------------
289 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
291 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
292 EVT_IDLE(wxApp::OnIdle
)
293 EVT_END_SESSION(wxApp::OnEndSession
)
294 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
297 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
299 class wxCallBaseCleanup
302 wxCallBaseCleanup(wxApp
*app
) : m_app(app
) { }
303 ~wxCallBaseCleanup() { if ( m_app
) m_app
->wxAppBase::CleanUp(); }
305 void Dismiss() { m_app
= NULL
; }
312 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
314 if ( !wxAppBase::Initialize(argc
, argv
) )
317 // ensure that base cleanup is done if we return too early
318 wxCallBaseCleanup
callBaseCleanup(this);
321 wxString tmp
= GetAppName();
322 tmp
+= wxT("ClassName");
323 wxCanvasClassName
= wxStrdup( tmp
.c_str() );
325 wxCanvasClassNameNR
= wxStrdup( tmp
.c_str() );
326 HWND hWnd
= FindWindow( wxCanvasClassNameNR
, NULL
);
329 SetForegroundWindow( (HWND
)(((DWORD
)hWnd
)|0x01) );
334 #if !defined(__WXMICROWIN__)
335 InitCommonControls();
336 #endif // !defined(__WXMICROWIN__)
338 #if defined(__SMARTPHONE__) || defined(__POCKETPC__)
339 SHInitExtraControls();
343 // Don't show a message box if a function such as SHGetFileInfo
344 // fails to find a device.
345 SetErrorMode(SEM_FAILCRITICALERRORS
|SEM_NOOPENFILEERRORBOX
);
350 RegisterWindowClasses();
352 wxWinHandleHash
= new wxWinHashTable(wxKEY_INTEGER
, 100);
354 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
355 wxSetKeyboardHook(true);
358 callBaseCleanup
.Dismiss();
363 // ---------------------------------------------------------------------------
364 // RegisterWindowClasses
365 // ---------------------------------------------------------------------------
367 // TODO we should only register classes really used by the app. For this it
368 // would be enough to just delay the class registration until an attempt
369 // to create a window of this class is made.
370 bool wxApp::RegisterWindowClasses()
373 wxZeroMemory(wndclass
);
375 // for each class we register one with CS_(V|H)REDRAW style and one
376 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
377 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
378 static const long styleNoRedraw
= CS_DBLCLKS
;
380 // the fields which are common to all classes
381 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
382 wndclass
.hInstance
= wxhInstance
;
383 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
385 // register the class for all normal windows
386 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_BTNFACE
+ 1);
387 wndclass
.lpszClassName
= wxCanvasClassName
;
388 wndclass
.style
= styleNormal
;
390 if ( !RegisterClass(&wndclass
) )
392 wxLogLastError(wxT("RegisterClass(frame)"));
396 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
397 wndclass
.style
= styleNoRedraw
;
399 if ( !RegisterClass(&wndclass
) )
401 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
404 // Register the MDI frame window class.
405 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
406 wndclass
.lpszClassName
= wxMDIFrameClassName
;
407 wndclass
.style
= styleNormal
;
409 if ( !RegisterClass(&wndclass
) )
411 wxLogLastError(wxT("RegisterClass(MDI parent)"));
414 // "no redraw" MDI frame
415 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
416 wndclass
.style
= styleNoRedraw
;
418 if ( !RegisterClass(&wndclass
) )
420 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
423 // Register the MDI child frame window class.
424 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
425 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
426 wndclass
.style
= styleNormal
;
428 if ( !RegisterClass(&wndclass
) )
430 wxLogLastError(wxT("RegisterClass(MDI child)"));
433 // "no redraw" MDI child frame
434 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
435 wndclass
.style
= styleNoRedraw
;
437 if ( !RegisterClass(&wndclass
) )
439 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
445 // ---------------------------------------------------------------------------
446 // UnregisterWindowClasses
447 // ---------------------------------------------------------------------------
449 bool wxApp::UnregisterWindowClasses()
453 #ifndef __WXMICROWIN__
454 // MDI frame window class.
455 if ( !::UnregisterClass(wxMDIFrameClassName
, wxhInstance
) )
457 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
462 // "no redraw" MDI frame
463 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw
, wxhInstance
) )
465 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
470 // MDI child frame window class.
471 if ( !::UnregisterClass(wxMDIChildFrameClassName
, wxhInstance
) )
473 wxLogLastError(wxT("UnregisterClass(MDI child)"));
478 // "no redraw" MDI child frame
479 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw
, wxhInstance
) )
481 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
487 if ( !::UnregisterClass(wxCanvasClassName
, wxhInstance
) )
489 wxLogLastError(wxT("UnregisterClass(canvas)"));
494 if ( !::UnregisterClass(wxCanvasClassNameNR
, wxhInstance
) )
496 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
500 #endif // __WXMICROWIN__
505 void wxApp::CleanUp()
507 // all objects pending for deletion must be deleted first, otherwise we
508 // would crash when they use wxWinHandleHash (and UnregisterWindowClasses()
509 // call wouldn't succeed as long as any windows still exist), so call the
510 // base class method first and only then do our clean up
511 wxAppBase::CleanUp();
513 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
514 wxSetKeyboardHook(false);
519 // for an EXE the classes are unregistered when it terminates but DLL may
520 // be loaded several times (load/unload/load) into the same process in
521 // which case the registration will fail after the first time if we don't
522 // unregister the classes now
523 UnregisterWindowClasses();
525 delete wxWinHandleHash
;
526 wxWinHandleHash
= NULL
;
529 free( wxCanvasClassName
);
530 free( wxCanvasClassNameNR
);
534 // ----------------------------------------------------------------------------
536 // ----------------------------------------------------------------------------
540 m_printMode
= wxPRINT_WINDOWS
;
547 // ----------------------------------------------------------------------------
548 // wxApp idle handling
549 // ----------------------------------------------------------------------------
551 void wxApp::OnIdle(wxIdleEvent
& event
)
553 wxAppBase::OnIdle(event
);
555 #if wxUSE_DC_CACHEING
556 // automated DC cache management: clear the cached DCs and bitmap
557 // if it's likely that the app has finished with them, that is, we
558 // get an idle event and we're not dragging anything.
559 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
561 #endif // wxUSE_DC_CACHEING
564 void wxApp::WakeUpIdle()
566 // Send the top window a dummy message so idle handler processing will
567 // start up again. Doing it this way ensures that the idle handler
568 // wakes up in the right thread (see also wxWakeUpMainThread() which does
569 // the same for the main app thread only)
570 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
573 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
575 // should never happen
576 wxLogLastError(wxT("PostMessage(WM_NULL)"));
581 // ----------------------------------------------------------------------------
582 // other wxApp event hanlders
583 // ----------------------------------------------------------------------------
585 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
588 GetTopWindow()->Close(true);
591 // Default behaviour: close the application with prompts. The
592 // user can veto the close, and therefore the end session.
593 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
597 if (!GetTopWindow()->Close(!event
.CanVeto()))
602 // ----------------------------------------------------------------------------
604 // ----------------------------------------------------------------------------
607 int wxApp::GetComCtl32Version()
609 #if defined(__WXMICROWIN__) || defined(__WXWINCE__)
614 // NB: this is MT-ok as in the worst case we'd compute s_verComCtl32 twice,
615 // but as its value should be the same both times it doesn't matter
616 static int s_verComCtl32
= -1;
618 if ( s_verComCtl32
== -1 )
620 // initally assume no comctl32.dll at all
623 // we're prepared to handle the errors
626 #if wxUSE_DYNLIB_CLASS
628 wxDynamicLibrary
dllComCtl32(_T("comctl32.dll"), wxDL_VERBATIM
);
630 // if so, then we can check for the version
631 if ( dllComCtl32
.IsLoaded() )
633 // now check if the function is available during run-time
634 wxDYNLIB_FUNCTION( DLLGETVERSIONPROC
, DllGetVersion
, dllComCtl32
);
635 if ( pfnDllGetVersion
)
638 dvi
.cbSize
= sizeof(dvi
);
640 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
643 wxLogApiError(_T("DllGetVersion"), hr
);
647 // this is incompatible with _WIN32_IE values, but
648 // compatible with the other values returned by
649 // GetComCtl32Version()
650 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
655 // if DllGetVersion() is unavailable either during compile or
656 // run-time, try to guess the version otherwise
657 if ( !s_verComCtl32
)
659 // InitCommonControlsEx is unique to 4.70 and later
660 void *pfn
= dllComCtl32
.GetSymbol(_T("InitCommonControlsEx"));
663 // not found, must be 4.00
668 // many symbols appeared in comctl32 4.71, could use any of
669 // them except may be DllInstall()
670 pfn
= dllComCtl32
.GetSymbol(_T("InitializeFlatSB"));
673 // not found, must be 4.70
678 // found, must be 4.71 or later
687 return s_verComCtl32
;
688 #endif // Microwin/!Microwin
691 // Yield to incoming messages
693 bool wxApp::Yield(bool onlyIfNeeded
)
696 static bool s_inYield
= false;
699 // disable log flushing from here because a call to wxYield() shouldn't
700 // normally result in message boxes popping up &c
708 wxFAIL_MSG( wxT("wxYield called recursively" ) );
716 // we don't want to process WM_QUIT from here - it should be processed in
717 // the main event loop in order to stop it
719 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
720 msg
.message
!= WM_QUIT
)
723 wxMutexGuiLeaveOrEnter();
724 #endif // wxUSE_THREADS
726 if ( !wxTheApp
->Dispatch() )
730 // if there are pending events, we must process them.
731 ProcessPendingEvents();
734 // let the logs be flashed again
745 // ----------------------------------------------------------------------------
746 // exception handling
747 // ----------------------------------------------------------------------------
749 bool wxApp::OnExceptionInMainLoop()
751 // ask the user about what to do: use the Win32 API function here as it
752 // could be dangerous to use any wxWidgets code in this state
757 _T("An unhandled exception occurred. Press \"Abort\" to \
758 terminate the program,\r\n\
759 \"Retry\" to exit the program normally and \"Ignore\" to try to continue."),
760 _T("Unhandled exception"),
761 MB_ABORTRETRYIGNORE
|
771 wxFAIL_MSG( _T("unexpected MessageBox() return code") );
782 #endif // wxUSE_EXCEPTIONS