1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utils.cpp
3 // Purpose: Various utilities
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"
34 #include "wx/msw/registry.h"
35 #include "wx/apptrait.h"
36 #include "wx/dynlib.h"
37 #include "wx/dynload.h"
38 #include "wx/scopeguard.h"
39 #include "wx/filename.h"
41 #include "wx/confbase.h" // for wxExpandEnvVars()
43 #include "wx/msw/private.h" // includes <windows.h>
44 #include "wx/msw/missing.h" // for CHARSET_HANGUL
46 #if defined(__CYGWIN__)
47 //CYGWIN gives annoying warning about runtime stuff if we don't do this
48 # define USE_SYS_TYPES_FD_SET
49 # include <sys/types.h>
52 // Doesn't work with Cygwin at present
53 #if wxUSE_SOCKETS && (defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) || defined(__CYGWIN32__))
54 // apparently we need to include winsock.h to get WSADATA and other stuff
55 // used in wxGetFullHostName() with the old mingw32 versions
59 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
67 #if defined(__CYGWIN__)
68 #include <sys/unistd.h>
70 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
73 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
74 // this (3.1 I believe) and how to test for it.
75 // If this works for Borland 4.0 as well, then no worries.
79 // VZ: there is some code using NetXXX() functions to get the full user name:
80 // I don't think it's a good idea because they don't work under Win95 and
81 // seem to return the same as wxGetUserId() under NT. If you really want
82 // to use them, just #define USE_NET_API
89 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
100 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
105 // For wxKillAllChildren
106 #include <tlhelp32.h>
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 // In the WIN.INI file
113 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__)
114 static const wxChar WX_SECTION
[] = wxT("wxWindows");
117 #if (!defined(USE_NET_API) && !defined(__WXWINCE__))
118 static const wxChar eUSERNAME
[] = wxT("UserName");
121 // ============================================================================
123 // ============================================================================
125 // ----------------------------------------------------------------------------
126 // get host name and related
127 // ----------------------------------------------------------------------------
129 // Get hostname only (without domain name)
130 bool wxGetHostName(wxChar
*WXUNUSED_IN_WINCE(buf
),
131 int WXUNUSED_IN_WINCE(maxSize
))
133 #if defined(__WXWINCE__)
137 DWORD nSize
= maxSize
;
138 if ( !::GetComputerName(buf
, &nSize
) )
140 wxLogLastError(wxT("GetComputerName"));
149 // get full hostname (with domain name if possible)
150 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
152 #if !defined( __WXMICROWIN__) && wxUSE_DYNLIB_CLASS && wxUSE_SOCKETS
153 // TODO should use GetComputerNameEx() when available
155 // we don't want to always link with Winsock DLL as we might not use it at
156 // all, so load it dynamically here if needed (and don't complain if it is
157 // missing, we handle this)
160 wxDynamicLibrary
dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM
);
161 if ( dllWinsock
.IsLoaded() )
163 typedef int (PASCAL
*WSAStartup_t
)(WORD
, WSADATA
*);
164 typedef int (PASCAL
*gethostname_t
)(char *, int);
165 typedef hostent
* (PASCAL
*gethostbyname_t
)(const char *);
166 typedef hostent
* (PASCAL
*gethostbyaddr_t
)(const char *, int , int);
167 typedef int (PASCAL
*WSACleanup_t
)(void);
169 #define LOAD_WINSOCK_FUNC(func) \
171 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
173 LOAD_WINSOCK_FUNC(WSAStartup
);
176 if ( pfnWSAStartup
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
178 LOAD_WINSOCK_FUNC(gethostname
);
181 if ( pfngethostname
)
184 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
186 // gethostname() won't usually include the DNS domain name,
187 // for this we need to work a bit more
188 if ( !strchr(bufA
, '.') )
190 LOAD_WINSOCK_FUNC(gethostbyname
);
192 struct hostent
*pHostEnt
= pfngethostbyname
193 ? pfngethostbyname(bufA
)
198 // Windows will use DNS internally now
199 LOAD_WINSOCK_FUNC(gethostbyaddr
);
201 pHostEnt
= pfngethostbyaddr
202 ? pfngethostbyaddr(pHostEnt
->h_addr
,
209 host
= wxString::FromAscii(pHostEnt
->h_name
);
215 LOAD_WINSOCK_FUNC(WSACleanup
);
222 wxStrlcpy(buf
, host
.c_str(), maxSize
);
228 #endif // !__WXMICROWIN__
230 return wxGetHostName(buf
, maxSize
);
233 // Get user ID e.g. jacs
234 bool wxGetUserId(wxChar
*WXUNUSED_IN_WINCE(buf
),
235 int WXUNUSED_IN_WINCE(maxSize
))
237 #if defined(__WXWINCE__)
241 DWORD nSize
= maxSize
;
242 if ( ::GetUserName(buf
, &nSize
) == 0 )
244 // actually, it does happen on Win9x if the user didn't log on
245 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
257 // Get user name e.g. Julian Smart
258 bool wxGetUserName(wxChar
*buf
, int maxSize
)
260 wxCHECK_MSG( buf
&& ( maxSize
> 0 ), false,
261 _T("empty buffer in wxGetUserName") );
262 #if defined(__WXWINCE__) && wxUSE_REGKEY
264 wxRegKey
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner"));
265 if(!key
.Open(wxRegKey::Read
))
268 if(!key
.QueryValue(wxT("Owner"),name
))
270 wxStrlcpy(buf
, name
.c_str(), maxSize
);
272 #elif defined(USE_NET_API)
273 CHAR szUserName
[256];
274 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
277 // TODO how to get the domain name?
280 // the code is based on the MSDN example (also see KB article Q119670)
281 WCHAR wszUserName
[256]; // Unicode user name
282 WCHAR wszDomain
[256];
285 USER_INFO_2
*ui2
; // User structure
287 // Convert ANSI user name and domain to Unicode
288 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
289 wszUserName
, WXSIZEOF(wszUserName
) );
290 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
291 wszDomain
, WXSIZEOF(wszDomain
) );
293 // Get the computer name of a DC for the domain.
294 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
296 wxLogError(wxT("Can not find domain controller"));
301 // Look up the user on the DC
302 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
303 (LPWSTR
)&wszUserName
,
304 2, // level - we want USER_INFO_2
312 case NERR_InvalidComputer
:
313 wxLogError(wxT("Invalid domain controller name."));
317 case NERR_UserNotFound
:
318 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
323 wxLogSysError(wxT("Can't get information about user"));
328 // Convert the Unicode full name to ANSI
329 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
330 buf
, maxSize
, NULL
, NULL
);
335 wxLogError(wxT("Couldn't look up full user name."));
338 #else // !USE_NET_API
339 // Could use NIS, MS-Mail or other site specific programs
340 // Use wxWidgets configuration data
341 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize
- 1) != 0;
344 ok
= wxGetUserId(buf
, maxSize
);
349 wxStrlcpy(buf
, wxT("Unknown User"), maxSize
);
356 const wxChar
* wxGetHomeDir(wxString
*pstr
)
358 wxString
& strDir
= *pstr
;
360 // first branch is for Cygwin
361 #if defined(__UNIX__) && !defined(__WINE__)
362 const wxChar
*szHome
= wxGetenv("HOME");
363 if ( szHome
== NULL
) {
365 wxLogWarning(_("can't find user's HOME, using current directory."));
371 // add a trailing slash if needed
372 if ( strDir
.Last() != wxT('/') )
376 // Cygwin returns unix type path but that does not work well
377 static wxChar windowsPath
[MAX_PATH
];
378 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
379 strDir
= windowsPath
;
381 #elif defined(__WXWINCE__)
386 // If we have a valid HOME directory, as is used on many machines that
387 // have unix utilities on them, we should use that.
388 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
390 if ( szHome
!= NULL
)
394 else // no HOME, try HOMEDRIVE/PATH
396 szHome
= wxGetenv(wxT("HOMEDRIVE"));
397 if ( szHome
!= NULL
)
399 szHome
= wxGetenv(wxT("HOMEPATH"));
401 if ( szHome
!= NULL
)
405 // the idea is that under NT these variables have default values
406 // of "%systemdrive%:" and "\\". As we don't want to create our
407 // config files in the root directory of the system drive, we will
408 // create it in our program's dir. However, if the user took care
409 // to set HOMEPATH to something other than "\\", we suppose that he
410 // knows what he is doing and use the supplied value.
411 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
416 if ( strDir
.empty() )
418 // If we have a valid USERPROFILE directory, as is the case in
419 // Windows NT, 2000 and XP, we should use that as our home directory.
420 szHome
= wxGetenv(wxT("USERPROFILE"));
422 if ( szHome
!= NULL
)
426 if ( !strDir
.empty() )
428 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
429 // value once again, it shouldn't hurt anyhow
430 strDir
= wxExpandEnvVars(strDir
);
432 else // fall back to the program directory
434 // extract the directory component of the program file name
435 wxFileName::SplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
439 return strDir
.c_str();
442 wxString
wxGetUserHome(const wxString
& user
)
446 if ( user
.empty() || user
== wxGetUserId() )
452 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
),
453 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pTotal
),
454 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pFree
))
463 // old w32api don't have ULARGE_INTEGER
464 #if defined(__WIN32__) && \
465 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
466 // GetDiskFreeSpaceEx() is not available under original Win95, check for
468 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
474 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
476 ::GetModuleHandle(_T("kernel32.dll")),
478 "GetDiskFreeSpaceExW"
480 "GetDiskFreeSpaceExA"
484 if ( pGetDiskFreeSpaceEx
)
486 ULARGE_INTEGER bytesFree
, bytesTotal
;
488 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
489 if ( !pGetDiskFreeSpaceEx(path
.fn_str(),
494 wxLogLastError(_T("GetDiskFreeSpaceEx"));
499 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
500 // two 32 bit fields which may be or may be not named - try to make it
501 // compile in all cases
502 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
510 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
512 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
);
519 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
521 *pFree
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
);
528 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
529 // should be used instead - but if it's not available, fall back on
530 // GetDiskFreeSpace() nevertheless...
532 DWORD lSectorsPerCluster
,
534 lNumberOfFreeClusters
,
535 lTotalNumberOfClusters
;
537 // FIXME: this is wrong, we should extract the root drive from path
538 // instead, but this is the job for wxFileName...
539 if ( !::GetDiskFreeSpace(path
.fn_str(),
542 &lNumberOfFreeClusters
,
543 &lTotalNumberOfClusters
) )
545 wxLogLastError(_T("GetDiskFreeSpace"));
550 wxDiskspaceSize_t lBytesPerCluster
= (wxDiskspaceSize_t
) lSectorsPerCluster
;
551 lBytesPerCluster
*= lBytesPerSector
;
555 *pTotal
= lBytesPerCluster
;
556 *pTotal
*= lTotalNumberOfClusters
;
561 *pFree
= lBytesPerCluster
;
562 *pFree
*= lNumberOfFreeClusters
;
571 // ----------------------------------------------------------------------------
573 // ----------------------------------------------------------------------------
575 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
576 wxString
*WXUNUSED_IN_WINCE(value
))
579 // no environment variables under CE
582 // first get the size of the buffer
583 DWORD dwRet
= ::GetEnvironmentVariable(var
.t_str(), NULL
, 0);
586 // this means that there is no such variable
592 (void)::GetEnvironmentVariable(var
.t_str(),
593 wxStringBuffer(*value
, dwRet
),
601 bool wxDoSetEnv(const wxString
& var
, const wxChar
*value
)
604 // no environment variables under CE
608 #else // !__WXWINCE__
609 // update the CRT environment if possible as people expect getenv() to also
610 // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
611 // the CRT does use Win32 call to update the process environment block so
612 // there is no need to call it)
614 // TODO: add checks for the other compilers (and update wxSetEnv()
615 // documentation in interface/wx/utils.h accordingly)
616 #if defined(__VISUALC__)
617 // notice that Microsoft _putenv() has different semantics from POSIX
618 // function with almost the same name: in particular it makes a copy of the
619 // string instead of using it as part of environment so we can safely call
620 // it here without going through all the troubles with wxSetEnvModule as in
621 // src/unix/utilsunx.cpp
622 wxString envstr
= var
;
626 _tputenv(envstr
.t_str());
627 #else // other compiler
628 if ( !::SetEnvironmentVariable(var
.t_str(), value
) )
630 wxLogLastError(_T("SetEnvironmentVariable"));
637 #endif // __WXWINCE__/!__WXWINCE__
640 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
642 return wxDoSetEnv(variable
, value
.t_str());
645 bool wxUnsetEnv(const wxString
& variable
)
647 return wxDoSetEnv(variable
, NULL
);
650 // ----------------------------------------------------------------------------
651 // process management
652 // ----------------------------------------------------------------------------
654 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
655 struct wxFindByPidParams
657 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
659 // the HWND used to return the result
662 // the PID we're looking from
665 wxDECLARE_NO_COPY_CLASS(wxFindByPidParams
);
668 // wxKill helper: EnumWindows() callback which is used to find the first (top
669 // level) window belonging to the given process
670 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
673 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
675 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
676 if ( pid
== params
->pid
)
678 // remember the window we found
681 // return FALSE to stop the enumeration
685 // continue enumeration
689 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
);
691 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
, int flags
)
693 if (flags
& wxKILL_CHILDREN
)
694 wxKillAllChildren(pid
, sig
, krc
);
696 // get the process handle to operate on
697 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
699 PROCESS_QUERY_INFORMATION
,
700 FALSE
, // not inheritable
702 if ( hProcess
== NULL
)
706 // recognize wxKILL_ACCESS_DENIED as special because this doesn't
707 // mean that the process doesn't exist and this is important for
708 // wxProcess::Exists()
709 *krc
= ::GetLastError() == ERROR_ACCESS_DENIED
710 ? wxKILL_ACCESS_DENIED
717 wxON_BLOCK_EXIT1(::CloseHandle
, hProcess
);
723 // kill the process forcefully returning -1 as error code
724 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
726 wxLogSysError(_("Failed to kill process %d"), pid
);
730 // this is not supposed to happen if we could open the
740 // do nothing, we just want to test for process existence
746 // any other signal means "terminate"
748 wxFindByPidParams params
;
749 params
.pid
= (DWORD
)pid
;
751 // EnumWindows() has nice semantics: it returns 0 if it found
752 // something or if an error occurred and non zero if it
753 // enumerated all the window
754 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
756 // did we find any window?
759 // tell the app to close
761 // NB: this is the harshest way, the app won't have an
762 // opportunity to save any files, for example, but
763 // this is probably what we want here. If not we
764 // can also use SendMesageTimeout(WM_CLOSE)
765 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
767 wxLogLastError(_T("PostMessage(WM_QUIT)"));
770 else // it was an error then
772 wxLogLastError(_T("EnumWindows"));
777 else // no windows for this PID
788 DWORD rc
wxDUMMY_INITIALIZE(0);
791 // as we wait for a short time, we can use just WaitForSingleObject()
792 // and not MsgWaitForMultipleObjects()
793 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
796 // process terminated
797 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
799 wxLogLastError(_T("GetExitCodeProcess"));
804 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
808 wxLogLastError(_T("WaitForSingleObject"));
821 // the return code is the same as from Unix kill(): 0 if killed
822 // successfully or -1 on error
823 if ( !ok
|| rc
== STILL_ACTIVE
)
832 typedef HANDLE (WINAPI
*CreateToolhelp32Snapshot_t
)(DWORD
,DWORD
);
833 typedef BOOL (WINAPI
*Process32_t
)(HANDLE
,LPPROCESSENTRY32
);
835 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot
;
836 Process32_t lpfProcess32First
, lpfProcess32Next
;
838 static void InitToolHelp32()
840 static bool s_initToolHelpDone
= false;
842 if (s_initToolHelpDone
)
845 s_initToolHelpDone
= true;
847 lpfCreateToolhelp32Snapshot
= NULL
;
848 lpfProcess32First
= NULL
;
849 lpfProcess32Next
= NULL
;
851 #if wxUSE_DYNLIB_CLASS
853 wxDynamicLibrary
dllKernel(_T("kernel32.dll"), wxDL_VERBATIM
);
855 // Get procedure addresses.
856 // We are linking to these functions of Kernel32
857 // explicitly, because otherwise a module using
858 // this code would fail to load under Windows NT,
859 // which does not have the Toolhelp32
860 // functions in the Kernel 32.
861 lpfCreateToolhelp32Snapshot
=
862 (CreateToolhelp32Snapshot_t
)dllKernel
.RawGetSymbol(_T("CreateToolhelp32Snapshot"));
865 (Process32_t
)dllKernel
.RawGetSymbol(_T("Process32First"));
868 (Process32_t
)dllKernel
.RawGetSymbol(_T("Process32Next"));
870 #endif // wxUSE_DYNLIB_CLASS
874 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
)
881 // If not implemented for this platform (e.g. NT 4.0), silently ignore
882 if (!lpfCreateToolhelp32Snapshot
|| !lpfProcess32First
|| !lpfProcess32Next
)
885 // Take a snapshot of all processes in the system.
886 HANDLE hProcessSnap
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
887 if (hProcessSnap
== INVALID_HANDLE_VALUE
) {
893 //Fill in the size of the structure before using it.
896 pe
.dwSize
= sizeof(PROCESSENTRY32
);
898 // Walk the snapshot of the processes, and for each process,
899 // kill it if its parent is pid.
900 if (!lpfProcess32First(hProcessSnap
, &pe
)) {
901 // Can't get first process.
904 CloseHandle (hProcessSnap
);
909 if (pe
.th32ParentProcessID
== (DWORD
) pid
) {
910 if (wxKill(pe
.th32ProcessID
, sig
, krc
))
913 } while (lpfProcess32Next (hProcessSnap
, &pe
));
919 // Execute a program in an Interactive Shell
920 bool wxShell(const wxString
& command
)
927 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
929 shell
= (wxChar
*) wxT("\\COMMAND.COM");
938 // pass the command to execute to the command processor
939 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
943 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
946 // Shutdown or reboot the PC
947 bool wxShutdown(int WXUNUSED_IN_WINCE(flags
))
952 #elif defined(__WIN32__)
955 if ( wxGetOsVersion(NULL
, NULL
) == wxOS_WINDOWS_NT
) // if is NT or 2K
957 // Get a token for this process.
959 bOK
= ::OpenProcessToken(GetCurrentProcess(),
960 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
964 TOKEN_PRIVILEGES tkp
;
966 // Get the LUID for the shutdown privilege.
967 bOK
= ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
968 &tkp
.Privileges
[0].Luid
) != 0;
972 tkp
.PrivilegeCount
= 1; // one privilege to set
973 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
975 // Get the shutdown privilege for this process.
976 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
977 (PTOKEN_PRIVILEGES
)NULL
, 0);
979 // Cannot test the return value of AdjustTokenPrivileges.
980 bOK
= ::GetLastError() == ERROR_SUCCESS
;
983 ::CloseHandle(hToken
);
990 if ( flags
& wxSHUTDOWN_FORCE
)
993 flags
&= ~wxSHUTDOWN_FORCE
;
998 case wxSHUTDOWN_POWEROFF
:
999 wFlags
|= EWX_POWEROFF
;
1002 case wxSHUTDOWN_REBOOT
:
1003 wFlags
|= EWX_REBOOT
;
1006 case wxSHUTDOWN_LOGOFF
:
1007 wFlags
|= EWX_LOGOFF
;
1011 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
1015 bOK
= ::ExitWindowsEx(wFlags
, 0) != 0;
1019 #endif // WinCE/!WinCE
1022 // ----------------------------------------------------------------------------
1024 // ----------------------------------------------------------------------------
1026 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1027 wxMemorySize
wxGetFreeMemory()
1029 #if defined(__WIN64__)
1030 MEMORYSTATUSEX memStatex
;
1031 memStatex
.dwLength
= sizeof (memStatex
);
1032 ::GlobalMemoryStatusEx (&memStatex
);
1033 return (wxMemorySize
)memStatex
.ullAvailPhys
;
1034 #else /* if defined(__WIN32__) */
1035 MEMORYSTATUS memStatus
;
1036 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1037 ::GlobalMemoryStatus(&memStatus
);
1038 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1042 unsigned long wxGetProcessId()
1044 return ::GetCurrentProcessId();
1050 ::MessageBeep((UINT
)-1); // default sound
1053 bool wxIsDebuggerRunning()
1055 #if wxUSE_DYNLIB_CLASS
1056 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1057 wxDynamicLibrary
dll(_T("kernel32.dll"), wxDL_VERBATIM
);
1059 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1060 if ( !dll
.HasSymbol(_T("IsDebuggerPresent")) )
1062 // no way to know, assume no
1066 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(_T("IsDebuggerPresent")))() != 0;
1072 // ----------------------------------------------------------------------------
1074 // ----------------------------------------------------------------------------
1076 // check if we're running under a server or workstation Windows system: it
1077 // returns true or false with obvious meaning as well as -1 if the system type
1078 // couldn't be determined
1080 // this function is currently private but we may want to expose it later if
1081 // it's really useful
1085 int wxIsWindowsServer()
1087 #ifdef VER_NT_WORKSTATION
1088 OSVERSIONINFOEX info
;
1091 info
.dwOSVersionInfoSize
= sizeof(info
);
1092 if ( ::GetVersionEx(reinterpret_cast<OSVERSIONINFO
*>(&info
)) )
1094 switch ( info
.wProductType
)
1096 case VER_NT_WORKSTATION
:
1100 case VER_NT_DOMAIN_CONTROLLER
:
1104 #endif // VER_NT_WORKSTATION
1109 } // anonymous namespace
1111 wxString
wxGetOsDescription()
1118 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1119 if ( ::GetVersionEx(&info
) )
1121 switch ( info
.dwPlatformId
)
1123 #ifdef VER_PLATFORM_WIN32_CE
1124 case VER_PLATFORM_WIN32_CE
:
1125 str
.Printf(_("Windows CE (%d.%d)"),
1126 info
.dwMajorVersion
,
1127 info
.dwMinorVersion
);
1130 case VER_PLATFORM_WIN32s
:
1131 str
= _("Win32s on Windows 3.1");
1134 case VER_PLATFORM_WIN32_WINDOWS
:
1135 switch (info
.dwMinorVersion
)
1138 if ( info
.szCSDVersion
[1] == 'B' ||
1139 info
.szCSDVersion
[1] == 'C' )
1141 str
= _("Windows 95 OSR2");
1145 str
= _("Windows 95");
1149 if ( info
.szCSDVersion
[1] == 'B' ||
1150 info
.szCSDVersion
[1] == 'C' )
1152 str
= _("Windows 98 SE");
1156 str
= _("Windows 98");
1160 str
= _("Windows ME");
1163 str
.Printf(_("Windows 9x (%d.%d)"),
1164 info
.dwMajorVersion
,
1165 info
.dwMinorVersion
);
1168 if ( !wxIsEmpty(info
.szCSDVersion
) )
1170 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
1174 case VER_PLATFORM_WIN32_NT
:
1175 switch ( info
.dwMajorVersion
)
1178 switch ( info
.dwMinorVersion
)
1181 str
.Printf(_("Windows 2000 (build %lu"),
1182 info
.dwBuildNumber
);
1186 // we can't distinguish between XP 64 and 2003
1187 // as they both are 5.2, so examine the product
1188 // type to resolve this ambiguity
1189 if ( wxIsWindowsServer() == 1 )
1191 str
.Printf(_("Windows Server 2003 (build %lu"),
1192 info
.dwBuildNumber
);
1195 //else: must be XP, fall through
1198 str
.Printf(_("Windows XP (build %lu"),
1199 info
.dwBuildNumber
);
1205 if ( info
.dwMinorVersion
== 0 )
1207 str
.Printf(_("Windows Vista (build %lu"),
1208 info
.dwBuildNumber
);
1215 str
.Printf(_("Windows NT %lu.%lu (build %lu"),
1216 info
.dwMajorVersion
,
1217 info
.dwMinorVersion
,
1218 info
.dwBuildNumber
);
1221 if ( !wxIsEmpty(info
.szCSDVersion
) )
1223 str
<< _T(", ") << info
.szCSDVersion
;
1227 if ( wxIsPlatform64Bit() )
1228 str
<< _(", 64-bit edition");
1234 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1240 bool wxIsPlatform64Bit()
1243 return true; // 64-bit programs run only on Win64
1244 #elif wxUSE_DYNLIB_CLASS // Win32
1245 // 32-bit programs run on both 32-bit and 64-bit Windows so check
1246 typedef BOOL (WINAPI
*IsWow64Process_t
)(HANDLE
, BOOL
*);
1248 wxDynamicLibrary
dllKernel32(_T("kernel32.dll"));
1249 IsWow64Process_t pfnIsWow64Process
=
1250 (IsWow64Process_t
)dllKernel32
.RawGetSymbol(_T("IsWow64Process"));
1253 if ( pfnIsWow64Process
)
1255 pfnIsWow64Process(::GetCurrentProcess(), &wow64
);
1257 //else: running under a system without Win64 support
1259 return wow64
!= FALSE
;
1262 #endif // Win64/Win32
1265 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1269 // this may be false, true or -1 if we tried to initialize but failed
1272 wxOperatingSystemId os
;
1278 // query the OS info only once as it's not supposed to change
1279 if ( !s_version
.initialized
)
1283 info
.dwOSVersionInfoSize
= sizeof(info
);
1284 if ( ::GetVersionEx(&info
) )
1286 s_version
.initialized
= true;
1288 #if defined(__WXWINCE__)
1289 s_version
.os
= wxOS_WINDOWS_CE
;
1290 #elif defined(__WXMICROWIN__)
1291 s_version
.os
= wxOS_WINDOWS_MICRO
;
1292 #else // "normal" desktop Windows system, use run-time detection
1293 switch ( info
.dwPlatformId
)
1295 case VER_PLATFORM_WIN32_NT
:
1296 s_version
.os
= wxOS_WINDOWS_NT
;
1299 case VER_PLATFORM_WIN32_WINDOWS
:
1300 s_version
.os
= wxOS_WINDOWS_9X
;
1303 #endif // Windows versions
1305 s_version
.verMaj
= info
.dwMajorVersion
;
1306 s_version
.verMin
= info
.dwMinorVersion
;
1308 else // GetVersionEx() failed
1310 s_version
.initialized
= -1;
1314 if ( s_version
.initialized
== 1 )
1317 *verMaj
= s_version
.verMaj
;
1319 *verMin
= s_version
.verMin
;
1322 // this works even if we were not initialized successfully as the initial
1323 // values of this field is 0 which is wxOS_UNKNOWN and exactly what we need
1324 return s_version
.os
;
1327 wxWinVersion
wxGetWinVersion()
1331 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
1333 case wxOS_WINDOWS_9X
:
1339 return wxWinVersion_95
;
1342 return wxWinVersion_98
;
1345 return wxWinVersion_ME
;
1350 case wxOS_WINDOWS_NT
:
1354 return wxWinVersion_NT3
;
1357 return wxWinVersion_NT4
;
1363 return wxWinVersion_2000
;
1366 return wxWinVersion_XP
;
1369 return wxWinVersion_2003
;
1374 return wxWinVersion_NT6
;
1379 // Do nothing just to silence GCC warning
1383 return wxWinVersion_Unknown
;
1386 // ----------------------------------------------------------------------------
1388 // ----------------------------------------------------------------------------
1390 void wxMilliSleep(unsigned long milliseconds
)
1392 ::Sleep(milliseconds
);
1395 void wxMicroSleep(unsigned long microseconds
)
1397 wxMilliSleep(microseconds
/1000);
1400 void wxSleep(int nSecs
)
1402 wxMilliSleep(1000*nSecs
);
1405 // ----------------------------------------------------------------------------
1406 // font encoding <-> Win32 codepage conversion functions
1407 // ----------------------------------------------------------------------------
1409 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1413 // although this function is supposed to return an exact match, do do
1414 // some mappings here for the most common case of "standard" encoding
1415 case wxFONTENCODING_SYSTEM
:
1416 return DEFAULT_CHARSET
;
1418 case wxFONTENCODING_ISO8859_1
:
1419 case wxFONTENCODING_ISO8859_15
:
1420 case wxFONTENCODING_CP1252
:
1421 return ANSI_CHARSET
;
1423 #if !defined(__WXMICROWIN__)
1424 // The following four fonts are multi-byte charsets
1425 case wxFONTENCODING_CP932
:
1426 return SHIFTJIS_CHARSET
;
1428 case wxFONTENCODING_CP936
:
1429 return GB2312_CHARSET
;
1432 case wxFONTENCODING_CP949
:
1433 return HANGUL_CHARSET
;
1436 case wxFONTENCODING_CP950
:
1437 return CHINESEBIG5_CHARSET
;
1439 // The rest are single byte encodings
1440 case wxFONTENCODING_CP1250
:
1441 return EASTEUROPE_CHARSET
;
1443 case wxFONTENCODING_CP1251
:
1444 return RUSSIAN_CHARSET
;
1446 case wxFONTENCODING_CP1253
:
1447 return GREEK_CHARSET
;
1449 case wxFONTENCODING_CP1254
:
1450 return TURKISH_CHARSET
;
1452 case wxFONTENCODING_CP1255
:
1453 return HEBREW_CHARSET
;
1455 case wxFONTENCODING_CP1256
:
1456 return ARABIC_CHARSET
;
1458 case wxFONTENCODING_CP1257
:
1459 return BALTIC_CHARSET
;
1461 case wxFONTENCODING_CP874
:
1462 return THAI_CHARSET
;
1463 #endif // !__WXMICROWIN__
1465 case wxFONTENCODING_CP437
:
1469 // no way to translate this encoding into a Windows charset
1474 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1475 // looks up the vlaues in the registry and the new one which is more
1476 // politically correct and has more chances to work on other Windows versions
1477 // as well but the old version is still needed for !wxUSE_FONTMAP case
1480 #include "wx/fontmap.h"
1482 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1484 // There don't seem to be symbolic names for
1485 // these under Windows so I just copied the
1486 // values from MSDN.
1492 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1493 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1494 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1495 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1496 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1497 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1498 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1499 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1500 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1501 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1502 case wxFONTENCODING_ISO8859_11
: ret
= 874; break;
1503 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1504 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1505 // case wxFONTENCODING_ISO8859_14: ret = 28604; break; // no correspondence on Windows
1506 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1508 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1509 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1511 case wxFONTENCODING_CP437
: ret
= 437; break;
1512 case wxFONTENCODING_CP850
: ret
= 850; break;
1513 case wxFONTENCODING_CP852
: ret
= 852; break;
1514 case wxFONTENCODING_CP855
: ret
= 855; break;
1515 case wxFONTENCODING_CP866
: ret
= 866; break;
1516 case wxFONTENCODING_CP874
: ret
= 874; break;
1517 case wxFONTENCODING_CP932
: ret
= 932; break;
1518 case wxFONTENCODING_CP936
: ret
= 936; break;
1519 case wxFONTENCODING_CP949
: ret
= 949; break;
1520 case wxFONTENCODING_CP950
: ret
= 950; break;
1521 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1522 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1523 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1524 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1525 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1526 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1527 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1528 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1530 case wxFONTENCODING_EUC_JP
: ret
= 20932; break;
1532 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1533 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1534 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1535 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1536 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1537 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1538 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1539 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1540 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1541 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1542 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1543 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1544 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1545 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1547 case wxFONTENCODING_ISO2022_JP
: ret
= 50222; break;
1549 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1550 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1555 if (::IsValidCodePage(ret
) == 0)
1559 if (::GetCPInfo(ret
, &info
) == 0)
1565 extern long wxCharsetToCodepage(const char *name
)
1567 // first get the font encoding for this charset
1571 wxFontEncoding enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
1572 if ( enc
== wxFONTENCODING_SYSTEM
)
1575 // the use the helper function
1576 return wxEncodingToCodepage(enc
);
1579 #else // !wxUSE_FONTMAP
1581 #include "wx/msw/registry.h"
1583 // this should work if Internet Exploiter is installed
1584 extern long wxCharsetToCodepage(const char *name
)
1592 wxString
path(wxT("MIME\\Database\\Charset\\"));
1595 // follow the alias loop
1598 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1603 // two cases: either there's an AliasForCharset string,
1604 // or there are Codepage and InternetEncoding dwords.
1605 // The InternetEncoding gives us the actual encoding,
1606 // the Codepage just says which Windows character set to
1607 // use when displaying the data.
1608 if (key
.HasValue(wxT("InternetEncoding")) &&
1609 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1612 // no encoding, see if it's an alias
1613 if (!key
.HasValue(wxT("AliasForCharset")) ||
1614 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1617 #endif // wxUSE_REGKEY
1622 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1625 Creates a hidden window with supplied window proc registering the class for
1626 it if necesssary (i.e. the first time only). Caller is responsible for
1627 destroying the window and unregistering the class (note that this must be
1628 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
1629 multiple times into/from the same process so we cna't rely on automatic
1630 Windows class unregistration).
1632 pclassname is a pointer to a caller stored classname, which must initially be
1633 NULL. classname is the desired wndclass classname. If function successfully
1634 registers the class, pclassname will be set to classname.
1636 extern "C" WXDLLIMPEXP_BASE HWND
1637 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1639 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1640 _T("NULL parameter in wxCreateHiddenWindow") );
1642 // register the class fi we need to first
1643 if ( *pclassname
== NULL
)
1646 wxZeroMemory(wndclass
);
1648 wndclass
.lpfnWndProc
= wndproc
;
1649 wndclass
.hInstance
= wxGetInstance();
1650 wndclass
.lpszClassName
= classname
;
1652 if ( !::RegisterClass(&wndclass
) )
1654 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1659 *pclassname
= classname
;
1662 // next create the window
1663 HWND hwnd
= ::CreateWindow
1677 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));