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
*buf
, int maxSize
)
132 #if defined(__WXWINCE__)
133 // GetComputerName() is not supported but the name seems to be stored in
134 // this location in the registry, at least for PPC2003 and WM5
136 wxRegKey
regKey(wxRegKey::HKLM
, wxT("Ident"));
137 if ( !regKey
.HasValue(wxT("Name")) ||
138 !regKey
.QueryValue(wxT("Name"), hostName
) )
141 wxStrlcpy(buf
, hostName
.wx_str(), maxSize
);
142 #else // !__WXWINCE__
143 DWORD nSize
= maxSize
;
144 if ( !::GetComputerName(buf
, &nSize
) )
146 wxLogLastError(wxT("GetComputerName"));
150 #endif // __WXWINCE__/!__WXWINCE__
155 // get full hostname (with domain name if possible)
156 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
158 #if !defined( __WXMICROWIN__) && wxUSE_DYNLIB_CLASS && wxUSE_SOCKETS
159 // TODO should use GetComputerNameEx() when available
161 // we don't want to always link with Winsock DLL as we might not use it at
162 // all, so load it dynamically here if needed (and don't complain if it is
163 // missing, we handle this)
166 wxDynamicLibrary
dllWinsock(wxT("ws2_32.dll"), wxDL_VERBATIM
);
167 if ( dllWinsock
.IsLoaded() )
169 typedef int (PASCAL
*WSAStartup_t
)(WORD
, WSADATA
*);
170 typedef int (PASCAL
*gethostname_t
)(char *, int);
171 typedef hostent
* (PASCAL
*gethostbyname_t
)(const char *);
172 typedef hostent
* (PASCAL
*gethostbyaddr_t
)(const char *, int , int);
173 typedef int (PASCAL
*WSACleanup_t
)(void);
175 #define LOAD_WINSOCK_FUNC(func) \
177 pfn ## func = (func ## _t)dllWinsock.GetSymbol(wxT(#func))
179 LOAD_WINSOCK_FUNC(WSAStartup
);
182 if ( pfnWSAStartup
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
184 LOAD_WINSOCK_FUNC(gethostname
);
187 if ( pfngethostname
)
190 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
192 // gethostname() won't usually include the DNS domain name,
193 // for this we need to work a bit more
194 if ( !strchr(bufA
, '.') )
196 LOAD_WINSOCK_FUNC(gethostbyname
);
198 struct hostent
*pHostEnt
= pfngethostbyname
199 ? pfngethostbyname(bufA
)
204 // Windows will use DNS internally now
205 LOAD_WINSOCK_FUNC(gethostbyaddr
);
207 pHostEnt
= pfngethostbyaddr
208 ? pfngethostbyaddr(pHostEnt
->h_addr
,
215 host
= wxString::FromAscii(pHostEnt
->h_name
);
221 LOAD_WINSOCK_FUNC(WSACleanup
);
228 wxStrlcpy(buf
, host
.c_str(), maxSize
);
234 #endif // !__WXMICROWIN__
236 return wxGetHostName(buf
, maxSize
);
239 // Get user ID e.g. jacs
240 bool wxGetUserId(wxChar
*WXUNUSED_IN_WINCE(buf
),
241 int WXUNUSED_IN_WINCE(maxSize
))
243 #if defined(__WXWINCE__)
247 DWORD nSize
= maxSize
;
248 if ( ::GetUserName(buf
, &nSize
) == 0 )
250 // actually, it does happen on Win9x if the user didn't log on
251 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
263 // Get user name e.g. Julian Smart
264 bool wxGetUserName(wxChar
*buf
, int maxSize
)
266 wxCHECK_MSG( buf
&& ( maxSize
> 0 ), false,
267 wxT("empty buffer in wxGetUserName") );
268 #if defined(__WXWINCE__) && wxUSE_REGKEY
270 wxRegKey
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner"));
271 if(!key
.Open(wxRegKey::Read
))
274 if(!key
.QueryValue(wxT("Owner"),name
))
276 wxStrlcpy(buf
, name
.c_str(), maxSize
);
278 #elif defined(USE_NET_API)
279 CHAR szUserName
[256];
280 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
283 // TODO how to get the domain name?
286 // the code is based on the MSDN example (also see KB article Q119670)
287 WCHAR wszUserName
[256]; // Unicode user name
288 WCHAR wszDomain
[256];
291 USER_INFO_2
*ui2
; // User structure
293 // Convert ANSI user name and domain to Unicode
294 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
295 wszUserName
, WXSIZEOF(wszUserName
) );
296 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
297 wszDomain
, WXSIZEOF(wszDomain
) );
299 // Get the computer name of a DC for the domain.
300 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
302 wxLogError(wxT("Can not find domain controller"));
307 // Look up the user on the DC
308 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
309 (LPWSTR
)&wszUserName
,
310 2, // level - we want USER_INFO_2
318 case NERR_InvalidComputer
:
319 wxLogError(wxT("Invalid domain controller name."));
323 case NERR_UserNotFound
:
324 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
329 wxLogSysError(wxT("Can't get information about user"));
334 // Convert the Unicode full name to ANSI
335 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
336 buf
, maxSize
, NULL
, NULL
);
341 wxLogError(wxT("Couldn't look up full user name."));
344 #else // !USE_NET_API
345 // Could use NIS, MS-Mail or other site specific programs
346 // Use wxWidgets configuration data
347 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize
- 1) != 0;
350 ok
= wxGetUserId(buf
, maxSize
);
355 wxStrlcpy(buf
, wxT("Unknown User"), maxSize
);
362 const wxChar
* wxGetHomeDir(wxString
*pstr
)
364 wxString
& strDir
= *pstr
;
366 // first branch is for Cygwin
367 #if defined(__UNIX__) && !defined(__WINE__)
368 const wxChar
*szHome
= wxGetenv("HOME");
369 if ( szHome
== NULL
) {
371 wxLogWarning(_("can't find user's HOME, using current directory."));
377 // add a trailing slash if needed
378 if ( strDir
.Last() != wxT('/') )
382 // Cygwin returns unix type path but that does not work well
383 static wxChar windowsPath
[MAX_PATH
];
384 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
385 strDir
= windowsPath
;
387 #elif defined(__WXWINCE__)
392 // If we have a valid HOME directory, as is used on many machines that
393 // have unix utilities on them, we should use that.
394 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
396 if ( szHome
!= NULL
)
400 else // no HOME, try HOMEDRIVE/PATH
402 szHome
= wxGetenv(wxT("HOMEDRIVE"));
403 if ( szHome
!= NULL
)
405 szHome
= wxGetenv(wxT("HOMEPATH"));
407 if ( szHome
!= NULL
)
411 // the idea is that under NT these variables have default values
412 // of "%systemdrive%:" and "\\". As we don't want to create our
413 // config files in the root directory of the system drive, we will
414 // create it in our program's dir. However, if the user took care
415 // to set HOMEPATH to something other than "\\", we suppose that he
416 // knows what he is doing and use the supplied value.
417 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
422 if ( strDir
.empty() )
424 // If we have a valid USERPROFILE directory, as is the case in
425 // Windows NT, 2000 and XP, we should use that as our home directory.
426 szHome
= wxGetenv(wxT("USERPROFILE"));
428 if ( szHome
!= NULL
)
432 if ( !strDir
.empty() )
434 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
435 // value once again, it shouldn't hurt anyhow
436 strDir
= wxExpandEnvVars(strDir
);
438 else // fall back to the program directory
440 // extract the directory component of the program file name
441 wxFileName::SplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
445 return strDir
.c_str();
448 wxString
wxGetUserHome(const wxString
& user
)
452 if ( user
.empty() || user
== wxGetUserId() )
458 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
),
459 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pTotal
),
460 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pFree
))
469 // old w32api don't have ULARGE_INTEGER
470 #if defined(__WIN32__) && \
471 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
472 // GetDiskFreeSpaceEx() is not available under original Win95, check for
474 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
480 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
482 ::GetModuleHandle(wxT("kernel32.dll")),
484 "GetDiskFreeSpaceExW"
486 "GetDiskFreeSpaceExA"
490 if ( pGetDiskFreeSpaceEx
)
492 ULARGE_INTEGER bytesFree
, bytesTotal
;
494 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
495 if ( !pGetDiskFreeSpaceEx(path
.fn_str(),
500 wxLogLastError(wxT("GetDiskFreeSpaceEx"));
505 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
506 // two 32 bit fields which may be or may be not named - try to make it
507 // compile in all cases
508 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
516 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
518 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
);
525 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
527 *pFree
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
);
534 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
535 // should be used instead - but if it's not available, fall back on
536 // GetDiskFreeSpace() nevertheless...
538 DWORD lSectorsPerCluster
,
540 lNumberOfFreeClusters
,
541 lTotalNumberOfClusters
;
543 // FIXME: this is wrong, we should extract the root drive from path
544 // instead, but this is the job for wxFileName...
545 if ( !::GetDiskFreeSpace(path
.fn_str(),
548 &lNumberOfFreeClusters
,
549 &lTotalNumberOfClusters
) )
551 wxLogLastError(wxT("GetDiskFreeSpace"));
556 wxDiskspaceSize_t lBytesPerCluster
= (wxDiskspaceSize_t
) lSectorsPerCluster
;
557 lBytesPerCluster
*= lBytesPerSector
;
561 *pTotal
= lBytesPerCluster
;
562 *pTotal
*= lTotalNumberOfClusters
;
567 *pFree
= lBytesPerCluster
;
568 *pFree
*= lNumberOfFreeClusters
;
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
581 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
582 wxString
*WXUNUSED_IN_WINCE(value
))
585 // no environment variables under CE
588 // first get the size of the buffer
589 DWORD dwRet
= ::GetEnvironmentVariable(var
.t_str(), NULL
, 0);
592 // this means that there is no such variable
598 (void)::GetEnvironmentVariable(var
.t_str(),
599 wxStringBuffer(*value
, dwRet
),
607 bool wxDoSetEnv(const wxString
& var
, const wxChar
*value
)
610 // no environment variables under CE
614 #else // !__WXWINCE__
615 // update the CRT environment if possible as people expect getenv() to also
616 // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
617 // the CRT does use Win32 call to update the process environment block so
618 // there is no need to call it)
620 // TODO: add checks for the other compilers (and update wxSetEnv()
621 // documentation in interface/wx/utils.h accordingly)
622 #if defined(__VISUALC__)
623 // notice that Microsoft _putenv() has different semantics from POSIX
624 // function with almost the same name: in particular it makes a copy of the
625 // string instead of using it as part of environment so we can safely call
626 // it here without going through all the troubles with wxSetEnvModule as in
627 // src/unix/utilsunx.cpp
628 wxString envstr
= var
;
632 _tputenv(envstr
.t_str());
633 #else // other compiler
634 if ( !::SetEnvironmentVariable(var
.t_str(), value
) )
636 wxLogLastError(wxT("SetEnvironmentVariable"));
643 #endif // __WXWINCE__/!__WXWINCE__
646 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
648 return wxDoSetEnv(variable
, value
.t_str());
651 bool wxUnsetEnv(const wxString
& variable
)
653 return wxDoSetEnv(variable
, NULL
);
656 // ----------------------------------------------------------------------------
657 // process management
658 // ----------------------------------------------------------------------------
660 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
661 struct wxFindByPidParams
663 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
665 // the HWND used to return the result
668 // the PID we're looking from
671 wxDECLARE_NO_COPY_CLASS(wxFindByPidParams
);
674 // wxKill helper: EnumWindows() callback which is used to find the first (top
675 // level) window belonging to the given process
676 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
679 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
681 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
682 if ( pid
== params
->pid
)
684 // remember the window we found
687 // return FALSE to stop the enumeration
691 // continue enumeration
695 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
);
697 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
, int flags
)
699 if (flags
& wxKILL_CHILDREN
)
700 wxKillAllChildren(pid
, sig
, krc
);
702 // get the process handle to operate on
703 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
705 PROCESS_QUERY_INFORMATION
,
706 FALSE
, // not inheritable
708 if ( hProcess
== NULL
)
712 // recognize wxKILL_ACCESS_DENIED as special because this doesn't
713 // mean that the process doesn't exist and this is important for
714 // wxProcess::Exists()
715 *krc
= ::GetLastError() == ERROR_ACCESS_DENIED
716 ? wxKILL_ACCESS_DENIED
723 wxON_BLOCK_EXIT1(::CloseHandle
, hProcess
);
729 // kill the process forcefully returning -1 as error code
730 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
732 wxLogSysError(_("Failed to kill process %d"), pid
);
736 // this is not supposed to happen if we could open the
746 // do nothing, we just want to test for process existence
752 // any other signal means "terminate"
754 wxFindByPidParams params
;
755 params
.pid
= (DWORD
)pid
;
757 // EnumWindows() has nice semantics: it returns 0 if it found
758 // something or if an error occurred and non zero if it
759 // enumerated all the window
760 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
762 // did we find any window?
765 // tell the app to close
767 // NB: this is the harshest way, the app won't have an
768 // opportunity to save any files, for example, but
769 // this is probably what we want here. If not we
770 // can also use SendMesageTimeout(WM_CLOSE)
771 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
773 wxLogLastError(wxT("PostMessage(WM_QUIT)"));
776 else // it was an error then
778 wxLogLastError(wxT("EnumWindows"));
783 else // no windows for this PID
794 DWORD rc
wxDUMMY_INITIALIZE(0);
797 // as we wait for a short time, we can use just WaitForSingleObject()
798 // and not MsgWaitForMultipleObjects()
799 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
802 // process terminated
803 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
805 wxLogLastError(wxT("GetExitCodeProcess"));
810 wxFAIL_MSG( wxT("unexpected WaitForSingleObject() return") );
814 wxLogLastError(wxT("WaitForSingleObject"));
827 // the return code is the same as from Unix kill(): 0 if killed
828 // successfully or -1 on error
829 if ( !ok
|| rc
== STILL_ACTIVE
)
838 typedef HANDLE (WINAPI
*CreateToolhelp32Snapshot_t
)(DWORD
,DWORD
);
839 typedef BOOL (WINAPI
*Process32_t
)(HANDLE
,LPPROCESSENTRY32
);
841 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot
;
842 Process32_t lpfProcess32First
, lpfProcess32Next
;
844 static void InitToolHelp32()
846 static bool s_initToolHelpDone
= false;
848 if (s_initToolHelpDone
)
851 s_initToolHelpDone
= true;
853 lpfCreateToolhelp32Snapshot
= NULL
;
854 lpfProcess32First
= NULL
;
855 lpfProcess32Next
= NULL
;
857 #if wxUSE_DYNLIB_CLASS
859 wxDynamicLibrary
dllKernel(wxT("kernel32.dll"), wxDL_VERBATIM
);
861 // Get procedure addresses.
862 // We are linking to these functions of Kernel32
863 // explicitly, because otherwise a module using
864 // this code would fail to load under Windows NT,
865 // which does not have the Toolhelp32
866 // functions in the Kernel 32.
867 lpfCreateToolhelp32Snapshot
=
868 (CreateToolhelp32Snapshot_t
)dllKernel
.RawGetSymbol(wxT("CreateToolhelp32Snapshot"));
871 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32First"));
874 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32Next"));
876 #endif // wxUSE_DYNLIB_CLASS
880 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
)
887 // If not implemented for this platform (e.g. NT 4.0), silently ignore
888 if (!lpfCreateToolhelp32Snapshot
|| !lpfProcess32First
|| !lpfProcess32Next
)
891 // Take a snapshot of all processes in the system.
892 HANDLE hProcessSnap
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
893 if (hProcessSnap
== INVALID_HANDLE_VALUE
) {
899 //Fill in the size of the structure before using it.
902 pe
.dwSize
= sizeof(PROCESSENTRY32
);
904 // Walk the snapshot of the processes, and for each process,
905 // kill it if its parent is pid.
906 if (!lpfProcess32First(hProcessSnap
, &pe
)) {
907 // Can't get first process.
910 CloseHandle (hProcessSnap
);
915 if (pe
.th32ParentProcessID
== (DWORD
) pid
) {
916 if (wxKill(pe
.th32ProcessID
, sig
, krc
))
919 } while (lpfProcess32Next (hProcessSnap
, &pe
));
925 // Execute a program in an Interactive Shell
926 bool wxShell(const wxString
& command
)
933 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
935 shell
= (wxChar
*) wxT("\\COMMAND.COM");
944 // pass the command to execute to the command processor
945 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
949 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
952 // Shutdown or reboot the PC
953 bool wxShutdown(int WXUNUSED_IN_WINCE(flags
))
958 #elif defined(__WIN32__)
961 if ( wxGetOsVersion(NULL
, NULL
) == wxOS_WINDOWS_NT
) // if is NT or 2K
963 // Get a token for this process.
965 bOK
= ::OpenProcessToken(GetCurrentProcess(),
966 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
970 TOKEN_PRIVILEGES tkp
;
972 // Get the LUID for the shutdown privilege.
973 bOK
= ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
974 &tkp
.Privileges
[0].Luid
) != 0;
978 tkp
.PrivilegeCount
= 1; // one privilege to set
979 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
981 // Get the shutdown privilege for this process.
982 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
983 (PTOKEN_PRIVILEGES
)NULL
, 0);
985 // Cannot test the return value of AdjustTokenPrivileges.
986 bOK
= ::GetLastError() == ERROR_SUCCESS
;
989 ::CloseHandle(hToken
);
996 if ( flags
& wxSHUTDOWN_FORCE
)
999 flags
&= ~wxSHUTDOWN_FORCE
;
1004 case wxSHUTDOWN_POWEROFF
:
1005 wFlags
|= EWX_POWEROFF
;
1008 case wxSHUTDOWN_REBOOT
:
1009 wFlags
|= EWX_REBOOT
;
1012 case wxSHUTDOWN_LOGOFF
:
1013 wFlags
|= EWX_LOGOFF
;
1017 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
1021 bOK
= ::ExitWindowsEx(wFlags
, 0) != 0;
1025 #endif // WinCE/!WinCE
1028 // ----------------------------------------------------------------------------
1030 // ----------------------------------------------------------------------------
1032 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1033 wxMemorySize
wxGetFreeMemory()
1035 #if defined(__WIN64__)
1036 MEMORYSTATUSEX memStatex
;
1037 memStatex
.dwLength
= sizeof (memStatex
);
1038 ::GlobalMemoryStatusEx (&memStatex
);
1039 return (wxMemorySize
)memStatex
.ullAvailPhys
;
1040 #else /* if defined(__WIN32__) */
1041 MEMORYSTATUS memStatus
;
1042 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1043 ::GlobalMemoryStatus(&memStatus
);
1044 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1048 unsigned long wxGetProcessId()
1050 return ::GetCurrentProcessId();
1056 ::MessageBeep((UINT
)-1); // default sound
1059 bool wxIsDebuggerRunning()
1061 #if wxUSE_DYNLIB_CLASS
1062 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1063 wxDynamicLibrary
dll(wxT("kernel32.dll"), wxDL_VERBATIM
);
1065 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1066 if ( !dll
.HasSymbol(wxT("IsDebuggerPresent")) )
1068 // no way to know, assume no
1072 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(wxT("IsDebuggerPresent")))() != 0;
1078 // ----------------------------------------------------------------------------
1080 // ----------------------------------------------------------------------------
1082 // check if we're running under a server or workstation Windows system: it
1083 // returns true or false with obvious meaning as well as -1 if the system type
1084 // couldn't be determined
1086 // this function is currently private but we may want to expose it later if
1087 // it's really useful
1091 int wxIsWindowsServer()
1093 #ifdef VER_NT_WORKSTATION
1094 OSVERSIONINFOEX info
;
1097 info
.dwOSVersionInfoSize
= sizeof(info
);
1098 if ( ::GetVersionEx(reinterpret_cast<OSVERSIONINFO
*>(&info
)) )
1100 switch ( info
.wProductType
)
1102 case VER_NT_WORKSTATION
:
1106 case VER_NT_DOMAIN_CONTROLLER
:
1110 #endif // VER_NT_WORKSTATION
1115 } // anonymous namespace
1117 wxString
wxGetOsDescription()
1124 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1125 if ( ::GetVersionEx(&info
) )
1127 switch ( info
.dwPlatformId
)
1129 #ifdef VER_PLATFORM_WIN32_CE
1130 case VER_PLATFORM_WIN32_CE
:
1131 str
.Printf(_("Windows CE (%d.%d)"),
1132 info
.dwMajorVersion
,
1133 info
.dwMinorVersion
);
1136 case VER_PLATFORM_WIN32s
:
1137 str
= _("Win32s on Windows 3.1");
1140 case VER_PLATFORM_WIN32_WINDOWS
:
1141 switch (info
.dwMinorVersion
)
1144 if ( info
.szCSDVersion
[1] == 'B' ||
1145 info
.szCSDVersion
[1] == 'C' )
1147 str
= _("Windows 95 OSR2");
1151 str
= _("Windows 95");
1155 if ( info
.szCSDVersion
[1] == 'B' ||
1156 info
.szCSDVersion
[1] == 'C' )
1158 str
= _("Windows 98 SE");
1162 str
= _("Windows 98");
1166 str
= _("Windows ME");
1169 str
.Printf(_("Windows 9x (%d.%d)"),
1170 info
.dwMajorVersion
,
1171 info
.dwMinorVersion
);
1174 if ( !wxIsEmpty(info
.szCSDVersion
) )
1176 str
<< wxT(" (") << info
.szCSDVersion
<< wxT(')');
1180 case VER_PLATFORM_WIN32_NT
:
1181 switch ( info
.dwMajorVersion
)
1184 switch ( info
.dwMinorVersion
)
1187 str
.Printf(_("Windows 2000 (build %lu"),
1188 info
.dwBuildNumber
);
1192 // we can't distinguish between XP 64 and 2003
1193 // as they both are 5.2, so examine the product
1194 // type to resolve this ambiguity
1195 if ( wxIsWindowsServer() == 1 )
1197 str
.Printf(_("Windows Server 2003 (build %lu"),
1198 info
.dwBuildNumber
);
1201 //else: must be XP, fall through
1204 str
.Printf(_("Windows XP (build %lu"),
1205 info
.dwBuildNumber
);
1211 if ( info
.dwMinorVersion
== 0 )
1213 str
.Printf(_("Windows Vista (build %lu"),
1214 info
.dwBuildNumber
);
1221 str
.Printf(_("Windows NT %lu.%lu (build %lu"),
1222 info
.dwMajorVersion
,
1223 info
.dwMinorVersion
,
1224 info
.dwBuildNumber
);
1227 if ( !wxIsEmpty(info
.szCSDVersion
) )
1229 str
<< wxT(", ") << info
.szCSDVersion
;
1233 if ( wxIsPlatform64Bit() )
1234 str
<< _(", 64-bit edition");
1240 wxFAIL_MSG( wxT("GetVersionEx() failed") ); // should never happen
1246 bool wxIsPlatform64Bit()
1249 return true; // 64-bit programs run only on Win64
1250 #elif wxUSE_DYNLIB_CLASS // Win32
1251 // 32-bit programs run on both 32-bit and 64-bit Windows so check
1252 typedef BOOL (WINAPI
*IsWow64Process_t
)(HANDLE
, BOOL
*);
1254 wxDynamicLibrary
dllKernel32(wxT("kernel32.dll"));
1255 IsWow64Process_t pfnIsWow64Process
=
1256 (IsWow64Process_t
)dllKernel32
.RawGetSymbol(wxT("IsWow64Process"));
1259 if ( pfnIsWow64Process
)
1261 pfnIsWow64Process(::GetCurrentProcess(), &wow64
);
1263 //else: running under a system without Win64 support
1265 return wow64
!= FALSE
;
1268 #endif // Win64/Win32
1271 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1275 // this may be false, true or -1 if we tried to initialize but failed
1278 wxOperatingSystemId os
;
1284 // query the OS info only once as it's not supposed to change
1285 if ( !s_version
.initialized
)
1289 info
.dwOSVersionInfoSize
= sizeof(info
);
1290 if ( ::GetVersionEx(&info
) )
1292 s_version
.initialized
= true;
1294 #if defined(__WXWINCE__)
1295 s_version
.os
= wxOS_WINDOWS_CE
;
1296 #elif defined(__WXMICROWIN__)
1297 s_version
.os
= wxOS_WINDOWS_MICRO
;
1298 #else // "normal" desktop Windows system, use run-time detection
1299 switch ( info
.dwPlatformId
)
1301 case VER_PLATFORM_WIN32_NT
:
1302 s_version
.os
= wxOS_WINDOWS_NT
;
1305 case VER_PLATFORM_WIN32_WINDOWS
:
1306 s_version
.os
= wxOS_WINDOWS_9X
;
1309 #endif // Windows versions
1311 s_version
.verMaj
= info
.dwMajorVersion
;
1312 s_version
.verMin
= info
.dwMinorVersion
;
1314 else // GetVersionEx() failed
1316 s_version
.initialized
= -1;
1320 if ( s_version
.initialized
== 1 )
1323 *verMaj
= s_version
.verMaj
;
1325 *verMin
= s_version
.verMin
;
1328 // this works even if we were not initialized successfully as the initial
1329 // values of this field is 0 which is wxOS_UNKNOWN and exactly what we need
1330 return s_version
.os
;
1333 wxWinVersion
wxGetWinVersion()
1337 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
1339 case wxOS_WINDOWS_9X
:
1345 return wxWinVersion_95
;
1348 return wxWinVersion_98
;
1351 return wxWinVersion_ME
;
1356 case wxOS_WINDOWS_NT
:
1360 return wxWinVersion_NT3
;
1363 return wxWinVersion_NT4
;
1369 return wxWinVersion_2000
;
1372 return wxWinVersion_XP
;
1375 return wxWinVersion_2003
;
1380 return wxWinVersion_NT6
;
1385 // Do nothing just to silence GCC warning
1389 return wxWinVersion_Unknown
;
1392 // ----------------------------------------------------------------------------
1394 // ----------------------------------------------------------------------------
1396 void wxMilliSleep(unsigned long milliseconds
)
1398 ::Sleep(milliseconds
);
1401 void wxMicroSleep(unsigned long microseconds
)
1403 wxMilliSleep(microseconds
/1000);
1406 void wxSleep(int nSecs
)
1408 wxMilliSleep(1000*nSecs
);
1411 // ----------------------------------------------------------------------------
1412 // font encoding <-> Win32 codepage conversion functions
1413 // ----------------------------------------------------------------------------
1415 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1419 // although this function is supposed to return an exact match, do do
1420 // some mappings here for the most common case of "standard" encoding
1421 case wxFONTENCODING_SYSTEM
:
1422 return DEFAULT_CHARSET
;
1424 case wxFONTENCODING_ISO8859_1
:
1425 case wxFONTENCODING_ISO8859_15
:
1426 case wxFONTENCODING_CP1252
:
1427 return ANSI_CHARSET
;
1429 #if !defined(__WXMICROWIN__)
1430 // The following four fonts are multi-byte charsets
1431 case wxFONTENCODING_CP932
:
1432 return SHIFTJIS_CHARSET
;
1434 case wxFONTENCODING_CP936
:
1435 return GB2312_CHARSET
;
1438 case wxFONTENCODING_CP949
:
1439 return HANGUL_CHARSET
;
1442 case wxFONTENCODING_CP950
:
1443 return CHINESEBIG5_CHARSET
;
1445 // The rest are single byte encodings
1446 case wxFONTENCODING_CP1250
:
1447 return EASTEUROPE_CHARSET
;
1449 case wxFONTENCODING_CP1251
:
1450 return RUSSIAN_CHARSET
;
1452 case wxFONTENCODING_CP1253
:
1453 return GREEK_CHARSET
;
1455 case wxFONTENCODING_CP1254
:
1456 return TURKISH_CHARSET
;
1458 case wxFONTENCODING_CP1255
:
1459 return HEBREW_CHARSET
;
1461 case wxFONTENCODING_CP1256
:
1462 return ARABIC_CHARSET
;
1464 case wxFONTENCODING_CP1257
:
1465 return BALTIC_CHARSET
;
1467 case wxFONTENCODING_CP874
:
1468 return THAI_CHARSET
;
1469 #endif // !__WXMICROWIN__
1471 case wxFONTENCODING_CP437
:
1475 // no way to translate this encoding into a Windows charset
1480 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1481 // looks up the vlaues in the registry and the new one which is more
1482 // politically correct and has more chances to work on other Windows versions
1483 // as well but the old version is still needed for !wxUSE_FONTMAP case
1486 #include "wx/fontmap.h"
1488 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1490 // There don't seem to be symbolic names for
1491 // these under Windows so I just copied the
1492 // values from MSDN.
1498 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1499 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1500 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1501 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1502 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1503 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1504 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1505 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1506 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1507 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1508 case wxFONTENCODING_ISO8859_11
: ret
= 874; break;
1509 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1510 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1511 // case wxFONTENCODING_ISO8859_14: ret = 28604; break; // no correspondence on Windows
1512 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1514 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1515 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1517 case wxFONTENCODING_CP437
: ret
= 437; break;
1518 case wxFONTENCODING_CP850
: ret
= 850; break;
1519 case wxFONTENCODING_CP852
: ret
= 852; break;
1520 case wxFONTENCODING_CP855
: ret
= 855; break;
1521 case wxFONTENCODING_CP866
: ret
= 866; break;
1522 case wxFONTENCODING_CP874
: ret
= 874; break;
1523 case wxFONTENCODING_CP932
: ret
= 932; break;
1524 case wxFONTENCODING_CP936
: ret
= 936; break;
1525 case wxFONTENCODING_CP949
: ret
= 949; break;
1526 case wxFONTENCODING_CP950
: ret
= 950; break;
1527 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1528 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1529 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1530 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1531 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1532 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1533 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1534 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1536 case wxFONTENCODING_EUC_JP
: ret
= 20932; break;
1538 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1539 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1540 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1541 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1542 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1543 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1544 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1545 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1546 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1547 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1548 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1549 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1550 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1551 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1553 case wxFONTENCODING_ISO2022_JP
: ret
= 50222; break;
1555 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1556 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1561 if (::IsValidCodePage(ret
) == 0)
1565 if (::GetCPInfo(ret
, &info
) == 0)
1571 extern long wxCharsetToCodepage(const char *name
)
1573 // first get the font encoding for this charset
1577 wxFontEncoding enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
1578 if ( enc
== wxFONTENCODING_SYSTEM
)
1581 // the use the helper function
1582 return wxEncodingToCodepage(enc
);
1585 #else // !wxUSE_FONTMAP
1587 #include "wx/msw/registry.h"
1589 // this should work if Internet Exploiter is installed
1590 extern long wxCharsetToCodepage(const char *name
)
1598 wxString
path(wxT("MIME\\Database\\Charset\\"));
1601 // follow the alias loop
1604 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1609 // two cases: either there's an AliasForCharset string,
1610 // or there are Codepage and InternetEncoding dwords.
1611 // The InternetEncoding gives us the actual encoding,
1612 // the Codepage just says which Windows character set to
1613 // use when displaying the data.
1614 if (key
.HasValue(wxT("InternetEncoding")) &&
1615 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1618 // no encoding, see if it's an alias
1619 if (!key
.HasValue(wxT("AliasForCharset")) ||
1620 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1623 #endif // wxUSE_REGKEY
1628 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1631 Creates a hidden window with supplied window proc registering the class for
1632 it if necesssary (i.e. the first time only). Caller is responsible for
1633 destroying the window and unregistering the class (note that this must be
1634 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
1635 multiple times into/from the same process so we cna't rely on automatic
1636 Windows class unregistration).
1638 pclassname is a pointer to a caller stored classname, which must initially be
1639 NULL. classname is the desired wndclass classname. If function successfully
1640 registers the class, pclassname will be set to classname.
1642 extern "C" WXDLLIMPEXP_BASE HWND
1643 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1645 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1646 wxT("NULL parameter in wxCreateHiddenWindow") );
1648 // register the class fi we need to first
1649 if ( *pclassname
== NULL
)
1652 wxZeroMemory(wndclass
);
1654 wndclass
.lpfnWndProc
= wndproc
;
1655 wndclass
.hInstance
= wxGetInstance();
1656 wndclass
.lpszClassName
= classname
;
1658 if ( !::RegisterClass(&wndclass
) )
1660 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1665 *pclassname
= classname
;
1668 // next create the window
1669 HWND hwnd
= ::CreateWindow
1683 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));