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"
40 #include "wx/confbase.h" // for wxExpandEnvVars()
42 #include "wx/msw/private.h" // includes <windows.h>
43 #include "wx/msw/missing.h" // CHARSET_HANGUL
45 #if defined(__CYGWIN__)
46 //CYGWIN gives annoying warning about runtime stuff if we don't do this
47 # define USE_SYS_TYPES_FD_SET
48 # include <sys/types.h>
51 // Doesn't work with Cygwin at present
52 #if wxUSE_SOCKETS && (defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) || defined(__CYGWIN32__))
53 // apparently we need to include winsock.h to get WSADATA and other stuff
54 // used in wxGetFullHostName() with the old mingw32 versions
60 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
68 #if defined(__CYGWIN__)
69 #include <sys/unistd.h>
71 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
74 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
75 // this (3.1 I believe) and how to test for it.
76 // If this works for Borland 4.0 as well, then no worries.
80 // VZ: there is some code using NetXXX() functions to get the full user name:
81 // I don't think it's a good idea because they don't work under Win95 and
82 // seem to return the same as wxGetUserId() under NT. If you really want
83 // to use them, just #define USE_NET_API
90 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
101 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
106 // For wxKillAllChildren
107 #include <tlhelp32.h>
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // In the WIN.INI file
114 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__)
115 static const wxChar WX_SECTION
[] = wxT("wxWindows");
118 #if (!defined(USE_NET_API) && !defined(__WXWINCE__))
119 static const wxChar eUSERNAME
[] = wxT("UserName");
122 // ============================================================================
124 // ============================================================================
126 // ----------------------------------------------------------------------------
127 // get host name and related
128 // ----------------------------------------------------------------------------
130 // Get hostname only (without domain name)
131 bool wxGetHostName(wxChar
*WXUNUSED_IN_WINCE(buf
),
132 int WXUNUSED_IN_WINCE(maxSize
))
134 #if defined(__WXWINCE__)
137 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
138 DWORD nSize
= maxSize
;
139 if ( !::GetComputerName(buf
, &nSize
) )
141 wxLogLastError(wxT("GetComputerName"));
149 const wxChar
*default_host
= wxT("noname");
151 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
152 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
154 wxStrncpy(buf
, sysname
, maxSize
- 1);
155 buf
[maxSize
] = wxT('\0');
156 return *buf
? true : false;
160 // get full hostname (with domain name if possible)
161 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
163 #if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER && wxUSE_SOCKETS
164 // TODO should use GetComputerNameEx() when available
166 // we don't want to always link with Winsock DLL as we might not use it at
167 // all, so load it dynamically here if needed (and don't complain if it is
168 // missing, we handle this)
171 wxDynamicLibrary
dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM
);
172 if ( dllWinsock
.IsLoaded() )
174 typedef int (PASCAL
*WSAStartup_t
)(WORD
, WSADATA
*);
175 typedef int (PASCAL
*gethostname_t
)(char *, int);
176 typedef hostent
* (PASCAL
*gethostbyname_t
)(const char *);
177 typedef hostent
* (PASCAL
*gethostbyaddr_t
)(const char *, int , int);
178 typedef int (PASCAL
*WSACleanup_t
)(void);
180 #define LOAD_WINSOCK_FUNC(func) \
182 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
184 LOAD_WINSOCK_FUNC(WSAStartup
);
187 if ( pfnWSAStartup
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
189 LOAD_WINSOCK_FUNC(gethostname
);
192 if ( pfngethostname
)
195 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
197 // gethostname() won't usually include the DNS domain name,
198 // for this we need to work a bit more
199 if ( !strchr(bufA
, '.') )
201 LOAD_WINSOCK_FUNC(gethostbyname
);
203 struct hostent
*pHostEnt
= pfngethostbyname
204 ? pfngethostbyname(bufA
)
209 // Windows will use DNS internally now
210 LOAD_WINSOCK_FUNC(gethostbyaddr
);
212 pHostEnt
= pfngethostbyaddr
213 ? pfngethostbyaddr(pHostEnt
->h_addr
,
220 host
= wxString::FromAscii(pHostEnt
->h_name
);
226 LOAD_WINSOCK_FUNC(WSACleanup
);
233 wxStrncpy(buf
, host
, maxSize
);
239 #endif // !__WXMICROWIN__
241 return wxGetHostName(buf
, maxSize
);
244 // Get user ID e.g. jacs
245 bool wxGetUserId(wxChar
*WXUNUSED_IN_WINCE(buf
),
246 int WXUNUSED_IN_WINCE(maxSize
))
248 #if defined(__WXWINCE__)
251 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
252 DWORD nSize
= maxSize
;
253 if ( ::GetUserName(buf
, &nSize
) == 0 )
255 // actually, it does happen on Win9x if the user didn't log on
256 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
265 #else // __WXMICROWIN__
267 const wxChar
*default_id
= wxT("anonymous");
269 // Can't assume we have NIS (PC-NFS) or some other ID daemon
271 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
272 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
274 // Use wxWidgets configuration data (comming soon)
275 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
279 wxStrncpy(buf
, user
, maxSize
- 1);
282 return *buf
? true : false;
286 // Get user name e.g. Julian Smart
287 bool wxGetUserName(wxChar
*buf
, int maxSize
)
289 wxCHECK_MSG( buf
&& ( maxSize
> 0 ), false,
290 _T("empty buffer in wxGetUserName") );
291 #if defined(__WXWINCE__)
293 wxRegKey
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner"));
294 if(!key
.Open(wxRegKey::Read
))
297 if(!key
.QueryValue(wxT("Owner"),name
))
299 wxStrncpy(buf
, name
.c_str(), maxSize
-1);
300 buf
[maxSize
-1] = _T('\0');
302 #elif defined(USE_NET_API)
303 CHAR szUserName
[256];
304 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
307 // TODO how to get the domain name?
310 // the code is based on the MSDN example (also see KB article Q119670)
311 WCHAR wszUserName
[256]; // Unicode user name
312 WCHAR wszDomain
[256];
315 USER_INFO_2
*ui2
; // User structure
317 // Convert ANSI user name and domain to Unicode
318 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
319 wszUserName
, WXSIZEOF(wszUserName
) );
320 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
321 wszDomain
, WXSIZEOF(wszDomain
) );
323 // Get the computer name of a DC for the domain.
324 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
326 wxLogError(wxT("Can not find domain controller"));
331 // Look up the user on the DC
332 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
333 (LPWSTR
)&wszUserName
,
334 2, // level - we want USER_INFO_2
342 case NERR_InvalidComputer
:
343 wxLogError(wxT("Invalid domain controller name."));
347 case NERR_UserNotFound
:
348 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
353 wxLogSysError(wxT("Can't get information about user"));
358 // Convert the Unicode full name to ANSI
359 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
360 buf
, maxSize
, NULL
, NULL
);
365 wxLogError(wxT("Couldn't look up full user name."));
368 #else // !USE_NET_API
369 // Could use NIS, MS-Mail or other site specific programs
370 // Use wxWidgets configuration data
371 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize
- 1) != 0;
374 ok
= wxGetUserId(buf
, maxSize
);
379 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
386 const wxChar
* wxGetHomeDir(wxString
*pstr
)
388 wxString
& strDir
= *pstr
;
390 // first branch is for Cygwin
391 #if defined(__UNIX__)
392 const wxChar
*szHome
= wxGetenv("HOME");
393 if ( szHome
== NULL
) {
395 wxLogWarning(_("can't find user's HOME, using current directory."));
401 // add a trailing slash if needed
402 if ( strDir
.Last() != wxT('/') )
406 // Cygwin returns unix type path but that does not work well
407 static wxChar windowsPath
[MAX_PATH
];
408 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
409 strDir
= windowsPath
;
411 #elif defined(__WXWINCE__)
416 // If we have a valid HOME directory, as is used on many machines that
417 // have unix utilities on them, we should use that.
418 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
420 if ( szHome
!= NULL
)
424 else // no HOME, try HOMEDRIVE/PATH
426 szHome
= wxGetenv(wxT("HOMEDRIVE"));
427 if ( szHome
!= NULL
)
429 szHome
= wxGetenv(wxT("HOMEPATH"));
431 if ( szHome
!= NULL
)
435 // the idea is that under NT these variables have default values
436 // of "%systemdrive%:" and "\\". As we don't want to create our
437 // config files in the root directory of the system drive, we will
438 // create it in our program's dir. However, if the user took care
439 // to set HOMEPATH to something other than "\\", we suppose that he
440 // knows what he is doing and use the supplied value.
441 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
446 if ( strDir
.empty() )
448 // If we have a valid USERPROFILE directory, as is the case in
449 // Windows NT, 2000 and XP, we should use that as our home directory.
450 szHome
= wxGetenv(wxT("USERPROFILE"));
452 if ( szHome
!= NULL
)
456 if ( !strDir
.empty() )
458 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
459 // value once again, it shouldn't hurt anyhow
460 strDir
= wxExpandEnvVars(strDir
);
462 else // fall back to the program directory
464 // extract the directory component of the program file name
465 wxSplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
469 return strDir
.c_str();
472 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
474 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
475 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
476 // static buffer and sometimes I don't even know what.
477 static wxString s_home
;
479 return (wxChar
*)wxGetHomeDir(&s_home
);
482 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
),
483 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pTotal
),
484 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pFree
))
493 // old w32api don't have ULARGE_INTEGER
494 #if defined(__WIN32__) && \
495 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
496 // GetDiskFreeSpaceEx() is not available under original Win95, check for
498 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
504 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
506 ::GetModuleHandle(_T("kernel32.dll")),
508 "GetDiskFreeSpaceExW"
510 "GetDiskFreeSpaceExA"
514 if ( pGetDiskFreeSpaceEx
)
516 ULARGE_INTEGER bytesFree
, bytesTotal
;
518 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
519 if ( !pGetDiskFreeSpaceEx(path
,
524 wxLogLastError(_T("GetDiskFreeSpaceEx"));
529 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
530 // two 32 bit fields which may be or may be not named - try to make it
531 // compile in all cases
532 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
540 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
542 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
);
549 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
551 *pFree
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
);
558 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
559 // should be used instead - but if it's not available, fall back on
560 // GetDiskFreeSpace() nevertheless...
562 DWORD lSectorsPerCluster
,
564 lNumberOfFreeClusters
,
565 lTotalNumberOfClusters
;
567 // FIXME: this is wrong, we should extract the root drive from path
568 // instead, but this is the job for wxFileName...
569 if ( !::GetDiskFreeSpace(path
,
572 &lNumberOfFreeClusters
,
573 &lTotalNumberOfClusters
) )
575 wxLogLastError(_T("GetDiskFreeSpace"));
580 wxDiskspaceSize_t lBytesPerCluster
= (wxDiskspaceSize_t
) lSectorsPerCluster
;
581 lBytesPerCluster
*= lBytesPerSector
;
585 *pTotal
= lBytesPerCluster
;
586 *pTotal
*= lTotalNumberOfClusters
;
591 *pFree
= lBytesPerCluster
;
592 *pFree
*= lNumberOfFreeClusters
;
601 // ----------------------------------------------------------------------------
603 // ----------------------------------------------------------------------------
605 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
606 wxString
*WXUNUSED_IN_WINCE(value
))
609 // no environment variables under CE
612 // first get the size of the buffer
613 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
616 // this means that there is no such variable
622 (void)::GetEnvironmentVariable(var
, wxStringBuffer(*value
, dwRet
),
630 bool wxSetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
631 const wxChar
*WXUNUSED_IN_WINCE(value
))
633 // some compilers have putenv() or _putenv() or _wputenv() but it's better
634 // to always use Win32 function directly instead of dealing with them
636 // no environment variables under CE
639 if ( !::SetEnvironmentVariable(var
, value
) )
641 wxLogLastError(_T("SetEnvironmentVariable"));
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 DECLARE_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(wxShutdownFlags
WXUNUSED_IN_WINCE(wFlags
))
952 #elif defined(__WIN32__)
955 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_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 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
968 &tkp
.Privileges
[0].Luid
);
970 tkp
.PrivilegeCount
= 1; // one privilege to set
971 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
973 // Get the shutdown privilege for this process.
974 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
975 (PTOKEN_PRIVILEGES
)NULL
, 0);
977 // Cannot test the return value of AdjustTokenPrivileges.
978 bOK
= ::GetLastError() == ERROR_SUCCESS
;
984 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
987 case wxSHUTDOWN_POWEROFF
:
988 flags
|= EWX_POWEROFF
;
991 case wxSHUTDOWN_REBOOT
:
996 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
1000 bOK
= ::ExitWindowsEx(flags
, 0) != 0;
1007 wxPowerType
wxGetPowerType()
1010 return wxPOWER_UNKNOWN
;
1013 wxBatteryState
wxGetBatteryState()
1016 return wxBATTERY_UNKNOWN_STATE
;
1019 // ----------------------------------------------------------------------------
1021 // ----------------------------------------------------------------------------
1023 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1024 wxMemorySize
wxGetFreeMemory()
1026 #if defined(__WIN64__)
1027 MEMORYSTATUSEX memStatex
;
1028 memStatex
.dwLength
= sizeof (memStatex
);
1029 ::GlobalMemoryStatusEx (&memStatex
);
1030 return (wxMemorySize
)memStatex
.ullAvailPhys
;
1031 #else /* if defined(__WIN32__) */
1032 MEMORYSTATUS memStatus
;
1033 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1034 ::GlobalMemoryStatus(&memStatus
);
1035 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1039 unsigned long wxGetProcessId()
1041 return ::GetCurrentProcessId();
1047 ::MessageBeep((UINT
)-1); // default sound
1050 bool wxIsDebuggerRunning()
1052 #if wxUSE_DYNLIB_CLASS
1053 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1054 wxDynamicLibrary
dll(_T("kernel32.dll"), wxDL_VERBATIM
);
1056 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1057 if ( !dll
.HasSymbol(_T("IsDebuggerPresent")) )
1059 // no way to know, assume no
1063 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(_T("IsDebuggerPresent")))() != 0;
1069 // ----------------------------------------------------------------------------
1071 // ----------------------------------------------------------------------------
1073 wxString
wxGetOsDescription()
1080 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1081 if ( ::GetVersionEx(&info
) )
1083 switch ( info
.dwPlatformId
)
1085 case VER_PLATFORM_WIN32s
:
1086 str
= _("Win32s on Windows 3.1");
1089 case VER_PLATFORM_WIN32_WINDOWS
:
1090 switch (info
.dwMinorVersion
)
1093 if ( info
.szCSDVersion
[1] == 'B' ||
1094 info
.szCSDVersion
[1] == 'C' )
1096 str
= _("Windows 95 OSR2");
1100 str
= _("Windows 95");
1104 if ( info
.szCSDVersion
[1] == 'B' ||
1105 info
.szCSDVersion
[1] == 'C' )
1107 str
= _("Windows 98 SE");
1111 str
= _("Windows 98");
1115 str
= _("Windows ME");
1118 str
.Printf(_("Windows 9x (%d.%d)"),
1119 info
.dwMajorVersion
,
1120 info
.dwMinorVersion
);
1123 if ( !wxIsEmpty(info
.szCSDVersion
) )
1125 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
1129 case VER_PLATFORM_WIN32_NT
:
1130 if ( info
.dwMajorVersion
== 5 )
1132 switch ( info
.dwMinorVersion
)
1135 str
.Printf(_("Windows 2000 (build %lu"),
1136 info
.dwBuildNumber
);
1139 str
.Printf(_("Windows XP (build %lu"),
1140 info
.dwBuildNumber
);
1143 str
.Printf(_("Windows Server 2003 (build %lu"),
1144 info
.dwBuildNumber
);
1148 if ( wxIsEmpty(str
) )
1150 str
.Printf(_("Windows NT %lu.%lu (build %lu"),
1151 info
.dwMajorVersion
,
1152 info
.dwMinorVersion
,
1153 info
.dwBuildNumber
);
1155 if ( !wxIsEmpty(info
.szCSDVersion
) )
1157 str
<< _T(", ") << info
.szCSDVersion
;
1165 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1171 wxToolkitInfo
& wxAppTraits::GetToolkitInfo()
1173 // cache the version info, it's not going to change
1175 // NB: this is MT-safe, we may use these static vars from different threads
1176 // but as they always have the same value it doesn't matter
1177 static int s_ver
= -1,
1187 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1188 if ( ::GetVersionEx(&info
) )
1190 s_major
= info
.dwMajorVersion
;
1191 s_minor
= info
.dwMinorVersion
;
1193 #ifdef __SMARTPHONE__
1194 s_ver
= wxWINDOWS_SMARTPHONE
;
1195 #elif defined(__POCKETPC__)
1196 s_ver
= wxWINDOWS_POCKETPC
;
1198 switch ( info
.dwPlatformId
)
1200 case VER_PLATFORM_WIN32s
:
1204 case VER_PLATFORM_WIN32_WINDOWS
:
1208 case VER_PLATFORM_WIN32_NT
:
1209 s_ver
= wxWINDOWS_NT
;
1212 case VER_PLATFORM_WIN32_CE
:
1213 s_ver
= wxWINDOWS_CE
;
1220 static wxToolkitInfo info
;
1221 info
.versionMajor
= s_major
;
1222 info
.versionMinor
= s_minor
;
1224 info
.name
= _T("wxBase");
1228 wxWinVersion
wxGetWinVersion()
1232 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
1240 return wxWinVersion_95
;
1243 return wxWinVersion_98
;
1246 return wxWinVersion_ME
;
1255 return wxWinVersion_NT3
;
1258 return wxWinVersion_NT4
;
1264 return wxWinVersion_2000
;
1267 return wxWinVersion_XP
;
1270 return wxWinVersion_2003
;
1275 return wxWinVersion_NT6
;
1281 return wxWinVersion_Unknown
;
1284 // ----------------------------------------------------------------------------
1286 // ----------------------------------------------------------------------------
1288 void wxMilliSleep(unsigned long milliseconds
)
1290 ::Sleep(milliseconds
);
1293 void wxMicroSleep(unsigned long microseconds
)
1295 wxMilliSleep(microseconds
/1000);
1298 void wxSleep(int nSecs
)
1300 wxMilliSleep(1000*nSecs
);
1303 // ----------------------------------------------------------------------------
1304 // font encoding <-> Win32 codepage conversion functions
1305 // ----------------------------------------------------------------------------
1307 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1311 // although this function is supposed to return an exact match, do do
1312 // some mappings here for the most common case of "standard" encoding
1313 case wxFONTENCODING_SYSTEM
:
1314 return DEFAULT_CHARSET
;
1316 case wxFONTENCODING_ISO8859_1
:
1317 case wxFONTENCODING_ISO8859_15
:
1318 case wxFONTENCODING_CP1252
:
1319 return ANSI_CHARSET
;
1321 #if !defined(__WXMICROWIN__)
1322 // The following four fonts are multi-byte charsets
1323 case wxFONTENCODING_CP932
:
1324 return SHIFTJIS_CHARSET
;
1326 case wxFONTENCODING_CP936
:
1327 return GB2312_CHARSET
;
1330 case wxFONTENCODING_CP949
:
1331 return HANGUL_CHARSET
;
1334 case wxFONTENCODING_CP950
:
1335 return CHINESEBIG5_CHARSET
;
1337 // The rest are single byte encodings
1338 case wxFONTENCODING_CP1250
:
1339 return EASTEUROPE_CHARSET
;
1341 case wxFONTENCODING_CP1251
:
1342 return RUSSIAN_CHARSET
;
1344 case wxFONTENCODING_CP1253
:
1345 return GREEK_CHARSET
;
1347 case wxFONTENCODING_CP1254
:
1348 return TURKISH_CHARSET
;
1350 case wxFONTENCODING_CP1255
:
1351 return HEBREW_CHARSET
;
1353 case wxFONTENCODING_CP1256
:
1354 return ARABIC_CHARSET
;
1356 case wxFONTENCODING_CP1257
:
1357 return BALTIC_CHARSET
;
1359 case wxFONTENCODING_CP874
:
1360 return THAI_CHARSET
;
1361 #endif // !__WXMICROWIN__
1363 case wxFONTENCODING_CP437
:
1367 // no way to translate this encoding into a Windows charset
1372 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1373 // looks up the vlaues in the registry and the new one which is more
1374 // politically correct and has more chances to work on other Windows versions
1375 // as well but the old version is still needed for !wxUSE_FONTMAP case
1378 #include "wx/fontmap.h"
1380 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1382 // There don't seem to be symbolic names for
1383 // these under Windows so I just copied the
1384 // values from MSDN.
1390 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1391 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1392 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1393 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1394 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1395 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1396 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1397 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1398 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1399 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1400 case wxFONTENCODING_ISO8859_11
: ret
= 28601; break;
1401 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1402 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1403 case wxFONTENCODING_ISO8859_14
: ret
= 28604; break;
1404 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1405 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1406 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1407 case wxFONTENCODING_CP437
: ret
= 437; break;
1408 case wxFONTENCODING_CP850
: ret
= 850; break;
1409 case wxFONTENCODING_CP852
: ret
= 852; break;
1410 case wxFONTENCODING_CP855
: ret
= 855; break;
1411 case wxFONTENCODING_CP866
: ret
= 866; break;
1412 case wxFONTENCODING_CP874
: ret
= 874; break;
1413 case wxFONTENCODING_CP932
: ret
= 932; break;
1414 case wxFONTENCODING_CP936
: ret
= 936; break;
1415 case wxFONTENCODING_CP949
: ret
= 949; break;
1416 case wxFONTENCODING_CP950
: ret
= 950; break;
1417 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1418 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1419 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1420 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1421 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1422 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1423 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1424 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1425 case wxFONTENCODING_EUC_JP
: ret
= 20932; break;
1426 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1427 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1428 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1429 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1430 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1431 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1432 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1433 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1434 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1435 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1436 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1437 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1438 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1439 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1440 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1441 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1445 if (::IsValidCodePage(ret
) == 0)
1449 if (::GetCPInfo(ret
, &info
) == 0)
1455 extern long wxCharsetToCodepage(const wxChar
*name
)
1457 // first get the font encoding for this charset
1461 wxFontEncoding enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
1462 if ( enc
== wxFONTENCODING_SYSTEM
)
1465 // the use the helper function
1466 return wxEncodingToCodepage(enc
);
1469 #else // !wxUSE_FONTMAP
1471 #include "wx/msw/registry.h"
1473 // this should work if Internet Exploiter is installed
1474 extern long wxCharsetToCodepage(const wxChar
*name
)
1481 wxString
path(wxT("MIME\\Database\\Charset\\"));
1484 // follow the alias loop
1487 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1492 // two cases: either there's an AliasForCharset string,
1493 // or there are Codepage and InternetEncoding dwords.
1494 // The InternetEncoding gives us the actual encoding,
1495 // the Codepage just says which Windows character set to
1496 // use when displaying the data.
1497 if (key
.HasValue(wxT("InternetEncoding")) &&
1498 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1501 // no encoding, see if it's an alias
1502 if (!key
.HasValue(wxT("AliasForCharset")) ||
1503 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1510 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1513 Creates a hidden window with supplied window proc registering the class for
1514 it if necesssary (i.e. the first time only). Caller is responsible for
1515 destroying the window and unregistering the class (note that this must be
1516 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
1517 multiple times into/from the same process so we cna't rely on automatic
1518 Windows class unregistration).
1520 pclassname is a pointer to a caller stored classname, which must initially be
1521 NULL. classname is the desired wndclass classname. If function successfully
1522 registers the class, pclassname will be set to classname.
1524 extern "C" WXDLLIMPEXP_BASE HWND
1525 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1527 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1528 _T("NULL parameter in wxCreateHiddenWindow") );
1530 // register the class fi we need to first
1531 if ( *pclassname
== NULL
)
1534 wxZeroMemory(wndclass
);
1536 wndclass
.lpfnWndProc
= wndproc
;
1537 wndclass
.hInstance
= wxGetInstance();
1538 wndclass
.lpszClassName
= classname
;
1540 if ( !::RegisterClass(&wndclass
) )
1542 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1547 *pclassname
= classname
;
1550 // next create the window
1551 HWND hwnd
= ::CreateWindow
1565 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));