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"
52 #include "wx/thread.h"
54 #include "wx/msw/private.h"
55 #include "wx/msw/dc.h"
56 #include "wx/msw/ole/oleutils.h"
57 #include "wx/msw/private/timer.h"
60 #include "wx/tooltip.h"
61 #endif // wxUSE_TOOLTIPS
63 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
64 // compilers don't support it (missing headers, libs, ...)
65 #if defined(__GNUWIN32_OLD__) || defined(__SYMANTEC__)
69 #endif // broken compilers
71 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
83 #include "wx/msw/missing.h"
85 // instead of including <shlwapi.h> which is not part of the core SDK and not
86 // shipped at all with other compilers, we always define the parts of it we
87 // need here ourselves
89 // NB: DLLVER_PLATFORM_WINDOWS will be defined if shlwapi.h had been somehow
91 #ifndef DLLVER_PLATFORM_WINDOWS
92 // hopefully we don't need to change packing as DWORDs should be already
97 DWORD dwMajorVersion
; // Major version
98 DWORD dwMinorVersion
; // Minor version
99 DWORD dwBuildNumber
; // Build number
100 DWORD dwPlatformID
; // DLLVER_PLATFORM_*
103 typedef HRESULT (CALLBACK
* DLLGETVERSIONPROC
)(DLLVERSIONINFO
*);
104 #endif // defined(DLLVERSIONINFO)
107 // ---------------------------------------------------------------------------
109 // ---------------------------------------------------------------------------
111 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
112 extern void wxSetKeyboardHook(bool doIt
);
115 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
116 // with NR suffix - wxWindow::MSWCreate() supposes this
118 WXDLLIMPEXP_CORE wxChar
*wxCanvasClassName
;
119 WXDLLIMPEXP_CORE wxChar
*wxCanvasClassNameNR
;
121 WXDLLIMPEXP_CORE
const wxChar
*wxCanvasClassName
= NULL
;
122 WXDLLIMPEXP_CORE
const wxChar
*wxCanvasClassNameNR
= NULL
;
124 WXDLLIMPEXP_CORE
const wxChar
*wxMDIFrameClassName
= NULL
;
125 WXDLLIMPEXP_CORE
const wxChar
*wxMDIFrameClassNameNoRedraw
= NULL
;
126 WXDLLIMPEXP_CORE
const wxChar
*wxMDIChildFrameClassName
= NULL
;
127 WXDLLIMPEXP_CORE
const wxChar
*wxMDIChildFrameClassNameNoRedraw
= NULL
;
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
135 // ===========================================================================
136 // wxGUIAppTraits implementation
137 // ===========================================================================
139 // private class which we use to pass parameters from BeforeChildWaitLoop() to
140 // AfterChildWaitLoop()
141 struct ChildWaitLoopData
143 ChildWaitLoopData(wxWindowDisabler
*wd_
, wxWindow
*winActive_
)
146 winActive
= winActive_
;
149 wxWindowDisabler
*wd
;
153 void *wxGUIAppTraits::BeforeChildWaitLoop()
156 We use a dirty hack here to disable all application windows (which we
157 must do because otherwise the calls to wxYield() could lead to some very
158 unexpected reentrancies in the users code) but to avoid losing
159 focus/activation entirely when the child process terminates which would
160 happen if we simply disabled everything using wxWindowDisabler. Indeed,
161 remember that Windows will never activate a disabled window and when the
162 last childs window is closed and Windows looks for a window to activate
163 all our windows are still disabled. There is no way to enable them in
164 time because we don't know when the childs windows are going to be
165 closed, so the solution we use here is to keep one special tiny frame
166 enabled all the time. Then when the child terminates it will get
167 activated and when we close it below -- after reenabling all the other
168 windows! -- the previously active window becomes activated again and
173 // first disable all existing windows
174 wxWindowDisabler
*wd
= new wxWindowDisabler
;
176 // then create an "invisible" frame: it has minimal size, is positioned
177 // (hopefully) outside the screen and doesn't appear on the taskbar
178 wxWindow
*winActive
= new wxFrame
180 wxTheApp
->GetTopWindow(),
183 wxPoint(32600, 32600),
185 wxDEFAULT_FRAME_STYLE
| wxFRAME_NO_TASKBAR
189 return new ChildWaitLoopData(wd
, winActive
);
192 void wxGUIAppTraits::AlwaysYield()
197 void wxGUIAppTraits::AfterChildWaitLoop(void *dataOrig
)
201 ChildWaitLoopData
* const data
= (ChildWaitLoopData
*)dataOrig
;
205 // finally delete the dummy frame and, as wd has been already destroyed and
206 // the other windows reenabled, the activation is going to return to the
207 // window which had had it before
208 data
->winActive
->Destroy();
210 // also delete the temporary data object itself
214 bool wxGUIAppTraits::DoMessageFromThreadWait()
216 // we should return false only if the app should exit, i.e. only if
217 // Dispatch() determines that the main event loop should terminate
218 wxEventLoopBase
* const evtLoop
= wxEventLoop::GetActive();
219 if ( !evtLoop
|| !evtLoop
->Pending() )
221 // no events means no quit event
225 return evtLoop
->Dispatch();
228 DWORD
wxGUIAppTraits::WaitForThread(WXHANDLE hThread
)
230 // if we don't have a running event loop, we shouldn't wait for the
231 // messages as we never remove them from the message queue and so we enter
232 // an infinite loop as MsgWaitForMultipleObjects() keeps returning
234 if ( !wxEventLoop::GetActive() )
235 return DoSimpleWaitForThread(hThread
);
237 return ::MsgWaitForMultipleObjects
239 1, // number of objects to wait for
240 (HANDLE
*)&hThread
, // the objects
241 false, // wait for any objects, not all
242 INFINITE
, // no timeout
243 QS_ALLINPUT
| // return as soon as there are any events
248 wxPortId
wxGUIAppTraits::GetToolkitVersion(int *majVer
, int *minVer
) const
253 // on Windows, the toolkit version is the same of the OS version
254 // as Windows integrates the OS kernel with the GUI toolkit.
255 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
256 if ( ::GetVersionEx(&info
) )
259 *majVer
= info
.dwMajorVersion
;
261 *minVer
= info
.dwMinorVersion
;
264 #if defined(__WXHANDHELD__) || defined(__WXWINCE__)
273 wxTimerImpl
*wxGUIAppTraits::CreateTimerImpl(wxTimer
*timer
)
275 return new wxMSWTimerImpl(timer
);
278 #endif // wxUSE_TIMER
280 wxEventLoopBase
* wxGUIAppTraits::CreateEventLoop()
282 return new wxEventLoop
;
285 // ---------------------------------------------------------------------------
286 // Stuff for using console from the GUI applications
287 // ---------------------------------------------------------------------------
291 #include <wx/dynlib.h>
297 Helper class to manipulate console from a GUI app.
299 Notice that console output is available in the GUI app only if:
300 - AttachConsole() returns TRUE (which means it never works under pre-XP)
301 - we have a valid STD_ERROR_HANDLE
302 - command history hasn't been changed since our startup
304 To check if all these conditions are verified, you need to simple call
305 IsOkToUse(). It will check the first two conditions above the first time it
306 is called (and if this fails, the subsequent calls will return immediately)
307 and also recheck the last one every time it is called.
309 class wxConsoleStderr
312 // default ctor does nothing, call Init() before using this class
315 m_hStderr
= INVALID_HANDLE_VALUE
;
325 if ( m_hStderr
!= INVALID_HANDLE_VALUE
)
327 if ( !::FreeConsole() )
329 wxLogLastError(_T("FreeConsole"));
334 // return true if we were successfully initialized and there had been no
335 // console activity which would interfere with our output since then
336 bool IsOkToUse() const
340 wxConsoleStderr
* const self
= wx_const_cast(wxConsoleStderr
*, this);
341 self
->m_ok
= self
->DoInit();
343 // no need to call IsHistoryUnchanged() as we just initialized
348 return m_ok
&& IsHistoryUnchanged();
352 // output the provided text on the console, return true if ok
353 bool Write(const wxString
& text
);
356 // called by Init() once only to do the real initialization
359 // retrieve the command line history into the provided buffer and return
361 int GetCommandHistory(wxWxCharBuffer
& buf
) const;
363 // check if the console history has changed
364 bool IsHistoryUnchanged() const;
366 int m_ok
; // initially -1, set to true or false by Init()
368 wxDynamicLibrary m_dllKernel32
;
370 HANDLE m_hStderr
; // console handle, if it's valid we must call
371 // FreeConsole() (even if m_ok != 1)
373 wxWxCharBuffer m_history
; // command history on startup
374 int m_historyLen
; // length command history buffer
376 wxCharBuffer m_data
; // data between empty line and cursor position
377 int m_dataLen
; // length data buffer
378 int m_dataLine
; // line offset
380 typedef DWORD (WINAPI
*GetConsoleCommandHistory_t
)(LPTSTR sCommands
,
383 typedef DWORD (WINAPI
*GetConsoleCommandHistoryLength_t
)(LPCTSTR sExeName
);
385 GetConsoleCommandHistory_t m_pfnGetConsoleCommandHistory
;
386 GetConsoleCommandHistoryLength_t m_pfnGetConsoleCommandHistoryLength
;
388 DECLARE_NO_COPY_CLASS(wxConsoleStderr
)
391 bool wxConsoleStderr::DoInit()
393 HANDLE hStderr
= ::GetStdHandle(STD_ERROR_HANDLE
);
395 if ( hStderr
== INVALID_HANDLE_VALUE
|| !hStderr
)
398 if ( !m_dllKernel32
.Load(_T("kernel32.dll")) )
401 typedef BOOL (WINAPI
*AttachConsole_t
)(DWORD dwProcessId
);
402 AttachConsole_t
wxDL_INIT_FUNC(pfn
, AttachConsole
, m_dllKernel32
);
404 if ( !pfnAttachConsole
|| !pfnAttachConsole(ATTACH_PARENT_PROCESS
) )
407 // console attached, set m_hStderr now to ensure that we free it in the
411 wxDL_INIT_FUNC_AW(m_pfn
, GetConsoleCommandHistory
, m_dllKernel32
);
412 if ( !m_pfnGetConsoleCommandHistory
)
415 wxDL_INIT_FUNC_AW(m_pfn
, GetConsoleCommandHistoryLength
, m_dllKernel32
);
416 if ( !m_pfnGetConsoleCommandHistoryLength
)
419 // remember the current command history to be able to compare with it later
420 // in IsHistoryUnchanged()
421 m_historyLen
= GetCommandHistory(m_history
);
426 // now find the first blank line above the current position
427 CONSOLE_SCREEN_BUFFER_INFO csbi
;
429 if ( !::GetConsoleScreenBufferInfo(m_hStderr
, &csbi
) )
431 wxLogLastError(_T("GetConsoleScreenBufferInfo"));
437 pos
.Y
= csbi
.dwCursorPosition
.Y
+ 1;
439 // we decide that a line is empty if first 4 characters are spaces
445 if ( !::ReadConsoleOutputCharacterA(m_hStderr
, buf
, WXSIZEOF(buf
),
448 wxLogLastError(_T("ReadConsoleOutputCharacterA"));
451 } while ( wxStrncmp(" ", buf
, WXSIZEOF(buf
)) != 0 );
453 // calculate line offset and length of data
454 m_dataLine
= csbi
.dwCursorPosition
.Y
- pos
.Y
;
455 m_dataLen
= m_dataLine
*csbi
.dwMaximumWindowSize
.X
+ csbi
.dwCursorPosition
.X
;
459 m_data
.extend(m_dataLen
);
460 if ( !::ReadConsoleOutputCharacterA(m_hStderr
, m_data
.data(), m_dataLen
,
463 wxLogLastError(_T("ReadConsoleOutputCharacterA"));
471 int wxConsoleStderr::GetCommandHistory(wxWxCharBuffer
& buf
) const
473 // these functions are internal and may only be called by cmd.exe
474 static const wxChar
*CMD_EXE
= _T("cmd.exe");
476 const int len
= m_pfnGetConsoleCommandHistoryLength(CMD_EXE
);
481 int len2
= m_pfnGetConsoleCommandHistory(buf
.data(), len
, CMD_EXE
);
484 // there seems to be a bug in the GetConsoleCommandHistoryA(), it
485 // returns the length of Unicode string and not ANSI one
487 #endif // !wxUSE_UNICODE
491 wxFAIL_MSG( _T("failed getting history?") );
498 bool wxConsoleStderr::IsHistoryUnchanged() const
500 wxASSERT_MSG( m_ok
== 1, _T("shouldn't be called if not initialized") );
502 // get (possibly changed) command history
503 wxWxCharBuffer history
;
504 const int historyLen
= GetCommandHistory(history
);
506 // and compare it with the original one
507 return historyLen
== m_historyLen
&& history
&&
508 memcmp(m_history
, history
, historyLen
) == 0;
511 bool wxConsoleStderr::Write(const wxString
& text
)
513 wxASSERT_MSG( m_hStderr
!= INVALID_HANDLE_VALUE
,
514 _T("should only be called if Init() returned true") );
516 // get current position
517 CONSOLE_SCREEN_BUFFER_INFO csbi
;
518 if ( !::GetConsoleScreenBufferInfo(m_hStderr
, &csbi
) )
520 wxLogLastError(_T("GetConsoleScreenBufferInfo"));
524 // and calculate new position (where is empty line)
525 csbi
.dwCursorPosition
.X
= 0;
526 csbi
.dwCursorPosition
.Y
-= m_dataLine
;
528 if ( !::SetConsoleCursorPosition(m_hStderr
, csbi
.dwCursorPosition
) )
530 wxLogLastError(_T("SetConsoleCursorPosition"));
535 if ( !::FillConsoleOutputCharacter(m_hStderr
, _T(' '), m_dataLen
,
536 csbi
.dwCursorPosition
, &ret
) )
538 wxLogLastError(_T("FillConsoleOutputCharacter"));
542 if ( !::WriteConsole(m_hStderr
, text
.wx_str(), text
.length(), &ret
, NULL
) )
544 wxLogLastError(_T("WriteConsole"));
548 WriteConsoleA(m_hStderr
, m_data
, m_dataLen
, &ret
, 0);
553 wxConsoleStderr s_consoleStderr
;
555 } // anonymous namespace
557 bool wxGUIAppTraits::CanUseStderr()
559 return s_consoleStderr
.IsOkToUse();
562 bool wxGUIAppTraits::WriteToStderr(const wxString
& text
)
564 return s_consoleStderr
.IsOkToUse() && s_consoleStderr
.Write(text
);
567 #endif // !__WXWINCE__
569 // ===========================================================================
570 // wxApp implementation
571 // ===========================================================================
573 int wxApp::m_nCmdShow
= SW_SHOWNORMAL
;
575 // ---------------------------------------------------------------------------
577 // ---------------------------------------------------------------------------
579 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
581 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
582 EVT_IDLE(wxApp::OnIdle
)
583 EVT_END_SESSION(wxApp::OnEndSession
)
584 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
587 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
589 class wxCallBaseCleanup
592 wxCallBaseCleanup(wxApp
*app
) : m_app(app
) { }
593 ~wxCallBaseCleanup() { if ( m_app
) m_app
->wxAppBase::CleanUp(); }
595 void Dismiss() { m_app
= NULL
; }
602 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
604 if ( !wxAppBase::Initialize(argc
, argv
) )
607 // ensure that base cleanup is done if we return too early
608 wxCallBaseCleanup
callBaseCleanup(this);
611 wxString tmp
= GetAppName();
612 tmp
+= wxT("ClassName");
613 wxCanvasClassName
= wxStrdup( tmp
.wc_str() );
615 wxCanvasClassNameNR
= wxStrdup( tmp
.wc_str() );
616 HWND hWnd
= FindWindow( wxCanvasClassNameNR
, NULL
);
619 SetForegroundWindow( (HWND
)(((DWORD
)hWnd
)|0x01) );
624 #if !defined(__WXMICROWIN__)
625 InitCommonControls();
626 #endif // !defined(__WXMICROWIN__)
628 #if defined(__SMARTPHONE__) || defined(__POCKETPC__)
629 SHInitExtraControls();
633 // Don't show a message box if a function such as SHGetFileInfo
634 // fails to find a device.
635 SetErrorMode(SEM_FAILCRITICALERRORS
|SEM_NOOPENFILEERRORBOX
);
640 RegisterWindowClasses();
642 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
643 wxSetKeyboardHook(true);
646 callBaseCleanup
.Dismiss();
651 // ---------------------------------------------------------------------------
652 // RegisterWindowClasses
653 // ---------------------------------------------------------------------------
655 // This function registers the given class name and stores a pointer to a
656 // heap-allocated copy of it at the specified location, it must be deleted
658 static void RegisterAndStoreClassName(const wxString
& uniqueClassName
,
659 const wxChar
**className
,
660 WNDCLASS
*lpWndClass
)
662 const size_t length
= uniqueClassName
.length() + 1; // for trailing NUL
663 wxChar
*newChars
= new wxChar
[length
];
664 wxStrncpy(newChars
, uniqueClassName
, length
);
665 *className
= newChars
;
666 lpWndClass
->lpszClassName
= *className
;
668 if ( !::RegisterClass(lpWndClass
) )
670 wxLogLastError(wxString::Format(wxT("RegisterClass(%s)"), newChars
));
674 // This function registers the class defined by the provided WNDCLASS struct
675 // contents using a unique name constructed from the specified base name and
676 // and a suffix unique to this library instance. It also stores the generated
677 // unique names for normal and "no redraw" versions of the class in the
678 // provided variables, caller must delete their contents later.
679 static void RegisterClassWithUniqueNames(const wxString
& baseName
,
680 const wxChar
**className
,
681 const wxChar
**classNameNR
,
682 WNDCLASS
*lpWndClass
)
684 // for each class we register one with CS_(V|H)REDRAW style and one
685 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
686 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
687 static const long styleNoRedraw
= CS_DBLCLKS
;
689 const wxString
uniqueSuffix(wxString::Format(wxT("@%p"), className
));
691 wxString
uniqueClassName(baseName
+ uniqueSuffix
);
692 lpWndClass
->style
= styleNormal
;
693 RegisterAndStoreClassName(uniqueClassName
, className
, lpWndClass
);
695 // NB: remember that code elsewhere supposes that no redraw class names
696 // use the same names as normal classes with "NR" suffix so we must put
697 // "NR" at the end instead of using more natural baseName+"NR"+suffix
698 wxString
uniqueClassNameNR(uniqueClassName
+ wxT("NR"));
699 lpWndClass
->style
= styleNoRedraw
;
700 RegisterAndStoreClassName(uniqueClassNameNR
, classNameNR
, lpWndClass
);
703 // TODO we should only register classes really used by the app. For this it
704 // would be enough to just delay the class registration until an attempt
705 // to create a window of this class is made.
706 bool wxApp::RegisterWindowClasses()
709 wxZeroMemory(wndclass
);
711 // the fields which are common to all classes
712 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
713 wndclass
.hInstance
= wxhInstance
;
714 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
716 // register the class for all normal windows and "no redraw" frames
717 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_BTNFACE
+ 1);
718 RegisterClassWithUniqueNames(wxT("wxWindowClass"),
720 &wxCanvasClassNameNR
,
723 // Register the MDI frame window class and "no redraw" MDI frame
724 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
725 RegisterClassWithUniqueNames(wxT("wxMDIFrameClass"),
726 &wxMDIFrameClassName
,
727 &wxMDIFrameClassNameNoRedraw
,
730 // Register the MDI child frame window class and "no redraw" MDI child frame
731 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
732 RegisterClassWithUniqueNames(wxT("wxMDIChildFrameClass"),
733 &wxMDIChildFrameClassName
,
734 &wxMDIChildFrameClassNameNoRedraw
,
740 // ---------------------------------------------------------------------------
741 // UnregisterWindowClasses
742 // ---------------------------------------------------------------------------
744 // This function unregisters the class with the given name and frees memory
745 // allocated for it by RegisterAndStoreClassName().
746 static bool UnregisterAndFreeClassName(const wxChar
**ppClassName
)
750 if ( !::UnregisterClass(*ppClassName
, wxhInstance
) )
753 wxString::Format(wxT("UnregisterClass(%s)"), *ppClassName
));
758 delete [] (wxChar
*) *ppClassName
;
764 bool wxApp::UnregisterWindowClasses()
768 #ifndef __WXMICROWIN__
769 if ( !UnregisterAndFreeClassName(&wxMDIFrameClassName
) )
772 if ( !UnregisterAndFreeClassName(&wxMDIFrameClassNameNoRedraw
) )
775 if ( !UnregisterAndFreeClassName(&wxMDIChildFrameClassName
) )
778 if ( !UnregisterAndFreeClassName(&wxMDIChildFrameClassNameNoRedraw
) )
781 if ( !UnregisterAndFreeClassName(&wxCanvasClassName
) )
784 if ( !UnregisterAndFreeClassName(&wxCanvasClassNameNR
) )
786 #endif // __WXMICROWIN__
791 void wxApp::CleanUp()
793 // all objects pending for deletion must be deleted first, otherwise
794 // UnregisterWindowClasses() call wouldn't succeed (because windows
795 // using the classes being unregistered still exist), so call the base
796 // class method first and only then do our clean up
797 wxAppBase::CleanUp();
799 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
800 wxSetKeyboardHook(false);
805 // for an EXE the classes are unregistered when it terminates but DLL may
806 // be loaded several times (load/unload/load) into the same process in
807 // which case the registration will fail after the first time if we don't
808 // unregister the classes now
809 UnregisterWindowClasses();
812 free( wxCanvasClassName
);
813 free( wxCanvasClassNameNR
);
817 // ----------------------------------------------------------------------------
819 // ----------------------------------------------------------------------------
823 m_printMode
= wxPRINT_WINDOWS
;
830 // ----------------------------------------------------------------------------
831 // wxApp idle handling
832 // ----------------------------------------------------------------------------
834 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
836 #if wxUSE_DC_CACHEING
837 // automated DC cache management: clear the cached DCs and bitmap
838 // if it's likely that the app has finished with them, that is, we
839 // get an idle event and we're not dragging anything.
840 if (!::GetKeyState(MK_LBUTTON
) && !::GetKeyState(MK_MBUTTON
) && !::GetKeyState(MK_RBUTTON
))
841 wxMSWDCImpl::ClearCache();
842 #endif // wxUSE_DC_CACHEING
845 void wxApp::WakeUpIdle()
847 // Send the top window a dummy message so idle handler processing will
848 // start up again. Doing it this way ensures that the idle handler
849 // wakes up in the right thread (see also wxWakeUpMainThread() which does
850 // the same for the main app thread only)
851 wxWindow
* const topWindow
= wxTheApp
->GetTopWindow();
854 HWND hwndTop
= GetHwndOf(topWindow
);
856 // Do not post WM_NULL if there's already a pending WM_NULL to avoid
857 // overflowing the message queue.
859 // Notice that due to a limitation of PeekMessage() API (which handles
860 // 0,0 range specially), we have to check the range from 0-1 instead.
861 // This still makes it possible to overflow the queue with WM_NULLs by
862 // interspersing the calles to WakeUpIdle() with windows creation but
863 // it should be rather hard to do it accidentally.
865 if ( !::PeekMessage(&msg
, hwndTop
, 0, 1, PM_NOREMOVE
) ||
866 ::PeekMessage(&msg
, hwndTop
, 1, 1, PM_NOREMOVE
) )
868 if ( !::PostMessage(hwndTop
, WM_NULL
, 0, 0) )
870 // should never happen
871 wxLogLastError(wxT("PostMessage(WM_NULL)"));
877 // ----------------------------------------------------------------------------
878 // other wxApp event hanlders
879 // ----------------------------------------------------------------------------
881 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
883 // Windows will terminate the process soon after we return from
884 // WM_ENDSESSION handler or when we delete our last window, so make sure we
885 // at least execute our cleanup code before
887 // prevent the window from being destroyed when the corresponding wxTLW is
888 // destroyed: this will result in a leak of a HWND, of course, but who
889 // cares when the process is being killed anyhow
890 if ( !wxTopLevelWindows
.empty() )
891 wxTopLevelWindows
[0]->SetHWND(0);
893 const int rc
= OnExit();
897 // calling exit() instead of ExitProcess() or not doing anything at all and
898 // being killed by Windows has the advantage of executing the dtors of
903 // Default behaviour: close the application with prompts. The
904 // user can veto the close, and therefore the end session.
905 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
909 if (!GetTopWindow()->Close(!event
.CanVeto()))
914 // ----------------------------------------------------------------------------
915 // system DLL versions
916 // ----------------------------------------------------------------------------
918 // these functions have trivial inline implementations for CE
921 #if wxUSE_DYNLIB_CLASS
926 // helper function: retrieve the DLL version by using DllGetVersion(), returns
927 // 0 if the DLL doesn't export such function
928 int CallDllGetVersion(wxDynamicLibrary
& dll
)
930 // now check if the function is available during run-time
931 wxDYNLIB_FUNCTION( DLLGETVERSIONPROC
, DllGetVersion
, dll
);
932 if ( !pfnDllGetVersion
)
936 dvi
.cbSize
= sizeof(dvi
);
938 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
941 wxLogApiError(_T("DllGetVersion"), hr
);
946 return 100*dvi
.dwMajorVersion
+ dvi
.dwMinorVersion
;
949 } // anonymous namespace
952 int wxApp::GetComCtl32Version()
956 // NB: this is MT-ok as in the worst case we'd compute s_verComCtl32 twice,
957 // but as its value should be the same both times it doesn't matter
958 static int s_verComCtl32
= -1;
960 if ( s_verComCtl32
== -1 )
962 // we're prepared to handle the errors
965 // the DLL should really be available
966 wxDynamicLibrary
dllComCtl32(_T("comctl32.dll"), wxDL_VERBATIM
);
967 if ( !dllComCtl32
.IsLoaded() )
973 // try DllGetVersion() for recent DLLs
974 s_verComCtl32
= CallDllGetVersion(dllComCtl32
);
976 // if DllGetVersion() is unavailable either during compile or
977 // run-time, try to guess the version otherwise
978 if ( !s_verComCtl32
)
980 // InitCommonControlsEx is unique to 4.70 and later
981 void *pfn
= dllComCtl32
.GetSymbol(_T("InitCommonControlsEx"));
984 // not found, must be 4.00
989 // many symbols appeared in comctl32 4.71, could use any of
990 // them except may be DllInstall()
991 pfn
= dllComCtl32
.GetSymbol(_T("InitializeFlatSB"));
994 // not found, must be 4.70
999 // found, must be 4.71 or later
1000 s_verComCtl32
= 471;
1006 return s_verComCtl32
;
1010 int wxApp::GetShell32Version()
1012 static int s_verShell32
= -1;
1013 if ( s_verShell32
== -1 )
1015 // we're prepared to handle the errors
1018 wxDynamicLibrary
dllShell32(_T("shell32.dll"), wxDL_VERBATIM
);
1019 if ( dllShell32
.IsLoaded() )
1021 s_verShell32
= CallDllGetVersion(dllShell32
);
1023 if ( !s_verShell32
)
1025 // there doesn't seem to be any way to distinguish between 4.00
1026 // and 4.70 (starting from 4.71 we have DllGetVersion()) so
1027 // just assume it is 4.0
1031 else // failed load the DLL?
1037 return s_verShell32
;
1040 #else // !wxUSE_DYNLIB_CLASS
1043 int wxApp::GetComCtl32Version()
1049 int wxApp::GetShell32Version()
1054 #endif // wxUSE_DYNLIB_CLASS/!wxUSE_DYNLIB_CLASS
1056 #endif // !__WXWINCE__
1058 // ----------------------------------------------------------------------------
1059 // Yield to incoming messages
1060 // ----------------------------------------------------------------------------
1062 bool wxApp::Yield(bool onlyIfNeeded
)
1065 static bool s_inYield
= false;
1068 // disable log flushing from here because a call to wxYield() shouldn't
1069 // normally result in message boxes popping up &c
1075 if ( !onlyIfNeeded
)
1077 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1085 // we don't want to process WM_QUIT from here - it should be processed in
1086 // the main event loop in order to stop it
1087 wxEventLoopGuarantor dummyLoopIfNeeded
;
1089 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1090 msg
.message
!= WM_QUIT
)
1093 wxMutexGuiLeaveOrEnter();
1094 #endif // wxUSE_THREADS
1096 if ( !wxTheApp
->Dispatch() )
1100 // if there are pending events, we must process them.
1101 ProcessPendingEvents();
1104 // let the logs be flashed again
1113 #if wxUSE_EXCEPTIONS
1115 // ----------------------------------------------------------------------------
1116 // exception handling
1117 // ----------------------------------------------------------------------------
1119 bool wxApp::OnExceptionInMainLoop()
1121 // ask the user about what to do: use the Win32 API function here as it
1122 // could be dangerous to use any wxWidgets code in this state
1127 _T("An unhandled exception occurred. Press \"Abort\" to \
1128 terminate the program,\r\n\
1129 \"Retry\" to exit the program normally and \"Ignore\" to try to continue."),
1130 _T("Unhandled exception"),
1131 MB_ABORTRETRYIGNORE
|
1141 wxFAIL_MSG( _T("unexpected MessageBox() return code") );
1152 #endif // wxUSE_EXCEPTIONS