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"     // for 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 
  58 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__) 
  66 #if defined(__CYGWIN__) 
  67     #include <sys/unistd.h> 
  69     #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path() 
  72 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs 
  73                     // this (3.1 I believe) and how to test for it. 
  74                     // If this works for Borland 4.0 as well, then no worries. 
  78 // VZ: there is some code using NetXXX() functions to get the full user name: 
  79 //     I don't think it's a good idea because they don't work under Win95 and 
  80 //     seem to return the same as wxGetUserId() under NT. If you really want 
  81 //     to use them, just #define USE_NET_API 
  88 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__) 
  99     #if !(defined(_MSC_VER) && (_MSC_VER > 800)) 
 104 // For wxKillAllChildren 
 105 #include <tlhelp32.h> 
 107 // ---------------------------------------------------------------------------- 
 109 // ---------------------------------------------------------------------------- 
 111 // In the WIN.INI file 
 112 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__) 
 113 static const wxChar WX_SECTION
[] = wxT("wxWindows"); 
 116 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) 
 117 static const wxChar eUSERNAME
[]  = wxT("UserName"); 
 120 // ============================================================================ 
 122 // ============================================================================ 
 124 // ---------------------------------------------------------------------------- 
 125 // get host name and related 
 126 // ---------------------------------------------------------------------------- 
 128 // Get hostname only (without domain name) 
 129 bool wxGetHostName(wxChar 
*WXUNUSED_IN_WINCE(buf
), 
 130                    int WXUNUSED_IN_WINCE(maxSize
)) 
 132 #if defined(__WXWINCE__) 
 135 #elif defined(__WIN32__) && !defined(__WXMICROWIN__) 
 136     DWORD nSize 
= maxSize
; 
 137     if ( !::GetComputerName(buf
, &nSize
) ) 
 139         wxLogLastError(wxT("GetComputerName")); 
 147     const wxChar 
*default_host 
= wxT("noname"); 
 149     if ((sysname 
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) { 
 150         GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize 
- 1); 
 152         wxStrncpy(buf
, sysname
, maxSize 
- 1); 
 153     buf
[maxSize
] = wxT('\0'); 
 154     return *buf 
? true : false; 
 158 // get full hostname (with domain name if possible) 
 159 bool wxGetFullHostName(wxChar 
*buf
, int maxSize
) 
 161 #if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER && wxUSE_SOCKETS 
 162     // TODO should use GetComputerNameEx() when available 
 164     // we don't want to always link with Winsock DLL as we might not use it at 
 165     // all, so load it dynamically here if needed (and don't complain if it is 
 166     // missing, we handle this) 
 169     wxDynamicLibrary 
dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM
); 
 170     if ( dllWinsock
.IsLoaded() ) 
 172         typedef int (PASCAL 
*WSAStartup_t
)(WORD
, WSADATA 
*); 
 173         typedef int (PASCAL 
*gethostname_t
)(char *, int); 
 174         typedef hostent
* (PASCAL 
*gethostbyname_t
)(const char *); 
 175         typedef hostent
* (PASCAL 
*gethostbyaddr_t
)(const char *, int , int); 
 176         typedef int (PASCAL 
*WSACleanup_t
)(void); 
 178         #define LOAD_WINSOCK_FUNC(func)                                       \ 
 180                 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func)) 
 182         LOAD_WINSOCK_FUNC(WSAStartup
); 
 185         if ( pfnWSAStartup 
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 ) 
 187             LOAD_WINSOCK_FUNC(gethostname
); 
 190             if ( pfngethostname 
) 
 193                 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 ) 
 195                     // gethostname() won't usually include the DNS domain name, 
 196                     // for this we need to work a bit more 
 197                     if ( !strchr(bufA
, '.') ) 
 199                         LOAD_WINSOCK_FUNC(gethostbyname
); 
 201                         struct hostent 
*pHostEnt 
= pfngethostbyname
 
 202                                                     ? pfngethostbyname(bufA
) 
 207                             // Windows will use DNS internally now 
 208                             LOAD_WINSOCK_FUNC(gethostbyaddr
); 
 210                             pHostEnt 
= pfngethostbyaddr
 
 211                                         ? pfngethostbyaddr(pHostEnt
->h_addr
, 
 218                             host 
= wxString::FromAscii(pHostEnt
->h_name
); 
 224             LOAD_WINSOCK_FUNC(WSACleanup
); 
 231                 wxStrncpy(buf
, host
, maxSize
); 
 237 #endif // !__WXMICROWIN__ 
 239     return wxGetHostName(buf
, maxSize
); 
 242 // Get user ID e.g. jacs 
 243 bool wxGetUserId(wxChar 
*WXUNUSED_IN_WINCE(buf
), 
 244                  int WXUNUSED_IN_WINCE(maxSize
)) 
 246 #if defined(__WXWINCE__) 
 249 #elif defined(__WIN32__) && !defined(__WXMICROWIN__) 
 250     DWORD nSize 
= maxSize
; 
 251     if ( ::GetUserName(buf
, &nSize
) == 0 ) 
 253         // actually, it does happen on Win9x if the user didn't log on 
 254         DWORD res 
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
); 
 263 #else   // __WXMICROWIN__ 
 265     const wxChar 
*default_id 
= wxT("anonymous"); 
 267     // Can't assume we have NIS (PC-NFS) or some other ID daemon 
 269     if ( (user 
= wxGetenv(wxT("USER"))) == NULL 
&& 
 270          (user 
= wxGetenv(wxT("LOGNAME"))) == NULL 
) 
 272         // Use wxWidgets configuration data (comming soon) 
 273         GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize 
- 1); 
 277         wxStrncpy(buf
, user
, maxSize 
- 1); 
 280     return *buf 
? true : false; 
 284 // Get user name e.g. Julian Smart 
 285 bool wxGetUserName(wxChar 
*buf
, int maxSize
) 
 287     wxCHECK_MSG( buf 
&& ( maxSize 
> 0 ), false, 
 288                     _T("empty buffer in wxGetUserName") ); 
 289 #if defined(__WXWINCE__) 
 291     wxRegKey 
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner")); 
 292     if(!key
.Open(wxRegKey::Read
)) 
 295     if(!key
.QueryValue(wxT("Owner"),name
)) 
 297     wxStrncpy(buf
, name
.c_str(), maxSize
-1); 
 298     buf
[maxSize
-1] = _T('\0'); 
 300 #elif defined(USE_NET_API) 
 301     CHAR szUserName
[256]; 
 302     if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) ) 
 305     // TODO how to get the domain name? 
 308     // the code is based on the MSDN example (also see KB article Q119670) 
 309     WCHAR wszUserName
[256];          // Unicode user name 
 310     WCHAR wszDomain
[256]; 
 313     USER_INFO_2 
*ui2
;         // User structure 
 315     // Convert ANSI user name and domain to Unicode 
 316     MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1, 
 317             wszUserName
, WXSIZEOF(wszUserName
) ); 
 318     MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1, 
 319             wszDomain
, WXSIZEOF(wszDomain
) ); 
 321     // Get the computer name of a DC for the domain. 
 322     if ( NetGetDCName( NULL
, wszDomain
, &ComputerName 
) != NERR_Success 
) 
 324         wxLogError(wxT("Can not find domain controller")); 
 329     // Look up the user on the DC 
 330     NET_API_STATUS status 
= NetUserGetInfo( (LPWSTR
)ComputerName
, 
 331             (LPWSTR
)&wszUserName
, 
 332             2, // level - we want USER_INFO_2 
 340         case NERR_InvalidComputer
: 
 341             wxLogError(wxT("Invalid domain controller name.")); 
 345         case NERR_UserNotFound
: 
 346             wxLogError(wxT("Invalid user name '%s'."), szUserName
); 
 351             wxLogSysError(wxT("Can't get information about user")); 
 356     // Convert the Unicode full name to ANSI 
 357     WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1, 
 358             buf
, maxSize
, NULL
, NULL 
); 
 363     wxLogError(wxT("Couldn't look up full user name.")); 
 366 #else  // !USE_NET_API 
 367     // Could use NIS, MS-Mail or other site specific programs 
 368     // Use wxWidgets configuration data 
 369     bool ok 
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize 
- 1) != 0; 
 372         ok 
= wxGetUserId(buf
, maxSize
); 
 377         wxStrncpy(buf
, wxT("Unknown User"), maxSize
); 
 384 const wxChar
* wxGetHomeDir(wxString 
*pstr
) 
 386     wxString
& strDir 
= *pstr
; 
 388     // first branch is for Cygwin 
 389 #if defined(__UNIX__) && !defined(__WINE__) 
 390     const wxChar 
*szHome 
= wxGetenv("HOME"); 
 391     if ( szHome 
== NULL 
) { 
 393       wxLogWarning(_("can't find user's HOME, using current directory.")); 
 399     // add a trailing slash if needed 
 400     if ( strDir
.Last() != wxT('/') ) 
 404         // Cygwin returns unix type path but that does not work well 
 405         static wxChar windowsPath
[MAX_PATH
]; 
 406         cygwin_conv_to_full_win32_path(strDir
, windowsPath
); 
 407         strDir 
= windowsPath
; 
 409 #elif defined(__WXWINCE__) 
 414     // If we have a valid HOME directory, as is used on many machines that 
 415     // have unix utilities on them, we should use that. 
 416     const wxChar 
*szHome 
= wxGetenv(wxT("HOME")); 
 418     if ( szHome 
!= NULL 
) 
 422     else // no HOME, try HOMEDRIVE/PATH 
 424         szHome 
= wxGetenv(wxT("HOMEDRIVE")); 
 425         if ( szHome 
!= NULL 
) 
 427         szHome 
= wxGetenv(wxT("HOMEPATH")); 
 429         if ( szHome 
!= NULL 
) 
 433             // the idea is that under NT these variables have default values 
 434             // of "%systemdrive%:" and "\\". As we don't want to create our 
 435             // config files in the root directory of the system drive, we will 
 436             // create it in our program's dir. However, if the user took care 
 437             // to set HOMEPATH to something other than "\\", we suppose that he 
 438             // knows what he is doing and use the supplied value. 
 439             if ( wxStrcmp(szHome
, wxT("\\")) == 0 ) 
 444     if ( strDir
.empty() ) 
 446         // If we have a valid USERPROFILE directory, as is the case in 
 447         // Windows NT, 2000 and XP, we should use that as our home directory. 
 448         szHome 
= wxGetenv(wxT("USERPROFILE")); 
 450         if ( szHome 
!= NULL 
) 
 454     if ( !strDir
.empty() ) 
 456         // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the 
 457         // value once again, it shouldn't hurt anyhow 
 458         strDir 
= wxExpandEnvVars(strDir
); 
 460     else // fall back to the program directory 
 462         // extract the directory component of the program file name 
 463         wxSplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
); 
 467     return strDir
.c_str(); 
 470 wxChar 
*wxGetUserHome(const wxString
& WXUNUSED(user
)) 
 472     // VZ: the old code here never worked for user != "" anyhow! Moreover, it 
 473     //     returned sometimes a malloc()'d pointer, sometimes a pointer to a 
 474     //     static buffer and sometimes I don't even know what. 
 475     static wxString s_home
; 
 477     return (wxChar 
*)wxGetHomeDir(&s_home
); 
 480 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
), 
 481                     wxDiskspaceSize_t 
*WXUNUSED_IN_WINCE(pTotal
), 
 482                     wxDiskspaceSize_t 
*WXUNUSED_IN_WINCE(pFree
)) 
 491 // old w32api don't have ULARGE_INTEGER 
 492 #if defined(__WIN32__) && \ 
 493     (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 )) 
 494     // GetDiskFreeSpaceEx() is not available under original Win95, check for 
 496     typedef BOOL (WINAPI 
*GetDiskFreeSpaceEx_t
)(LPCTSTR
, 
 502         pGetDiskFreeSpaceEx 
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
 
 504                                 ::GetModuleHandle(_T("kernel32.dll")), 
 506                                 "GetDiskFreeSpaceExW" 
 508                                 "GetDiskFreeSpaceExA" 
 512     if ( pGetDiskFreeSpaceEx 
) 
 514         ULARGE_INTEGER bytesFree
, bytesTotal
; 
 516         // may pass the path as is, GetDiskFreeSpaceEx() is smart enough 
 517         if ( !pGetDiskFreeSpaceEx(path
, 
 522             wxLogLastError(_T("GetDiskFreeSpaceEx")); 
 527         // ULARGE_INTEGER is a union of a 64 bit value and a struct containing 
 528         // two 32 bit fields which may be or may be not named - try to make it 
 529         // compile in all cases 
 530 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT) 
 538             *pTotal 
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
); 
 540             *pTotal 
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
); 
 547             *pFree 
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
); 
 549             *pFree 
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
); 
 556         // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx() 
 557         // should be used instead - but if it's not available, fall back on 
 558         // GetDiskFreeSpace() nevertheless... 
 560         DWORD lSectorsPerCluster
, 
 562               lNumberOfFreeClusters
, 
 563               lTotalNumberOfClusters
; 
 565         // FIXME: this is wrong, we should extract the root drive from path 
 566         //        instead, but this is the job for wxFileName... 
 567         if ( !::GetDiskFreeSpace(path
, 
 570                                  &lNumberOfFreeClusters
, 
 571                                  &lTotalNumberOfClusters
) ) 
 573             wxLogLastError(_T("GetDiskFreeSpace")); 
 578         wxDiskspaceSize_t lBytesPerCluster 
= (wxDiskspaceSize_t
) lSectorsPerCluster
; 
 579         lBytesPerCluster 
*= lBytesPerSector
; 
 583             *pTotal 
= lBytesPerCluster
; 
 584             *pTotal 
*= lTotalNumberOfClusters
; 
 589             *pFree 
= lBytesPerCluster
; 
 590             *pFree 
*= lNumberOfFreeClusters
; 
 599 // ---------------------------------------------------------------------------- 
 601 // ---------------------------------------------------------------------------- 
 603 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
), 
 604               wxString 
*WXUNUSED_IN_WINCE(value
)) 
 607     // no environment variables under CE 
 610     // first get the size of the buffer 
 611     DWORD dwRet 
= ::GetEnvironmentVariable(var
, NULL
, 0); 
 614         // this means that there is no such variable 
 620         (void)::GetEnvironmentVariable(var
, wxStringBuffer(*value
, dwRet
), 
 628 bool wxDoSetEnv(const wxString
& WXUNUSED_IN_WINCE(var
), 
 629                 const wxChar 
*WXUNUSED_IN_WINCE(value
)) 
 631     // some compilers have putenv() or _putenv() or _wputenv() but it's better 
 632     // to always use Win32 function directly instead of dealing with them 
 634     // no environment variables under CE 
 637     if ( !::SetEnvironmentVariable(var
.wx_str(), value
) ) 
 639         wxLogLastError(_T("SetEnvironmentVariable")); 
 648 bool wxSetEnv(const wxString
& variable
, const wxString
& value
) 
 650     return wxDoSetEnv(variable
, value
.wx_str()); 
 653 bool wxUnsetEnv(const wxString
& variable
) 
 655     return wxDoSetEnv(variable
, NULL
); 
 658 // ---------------------------------------------------------------------------- 
 659 // process management 
 660 // ---------------------------------------------------------------------------- 
 662 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc() 
 663 struct wxFindByPidParams
 
 665     wxFindByPidParams() { hwnd 
= 0; pid 
= 0; } 
 667     // the HWND used to return the result 
 670     // the PID we're looking from 
 673     DECLARE_NO_COPY_CLASS(wxFindByPidParams
) 
 676 // wxKill helper: EnumWindows() callback which is used to find the first (top 
 677 // level) window belonging to the given process 
 678 BOOL CALLBACK 
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
) 
 681     (void)::GetWindowThreadProcessId(hwnd
, &pid
); 
 683     wxFindByPidParams 
*params 
= (wxFindByPidParams 
*)lParam
; 
 684     if ( pid 
== params
->pid 
) 
 686         // remember the window we found 
 689         // return FALSE to stop the enumeration 
 693     // continue enumeration 
 697 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError 
*krc
); 
 699 int wxKill(long pid
, wxSignal sig
, wxKillError 
*krc
, int flags
) 
 701     if (flags 
& wxKILL_CHILDREN
) 
 702         wxKillAllChildren(pid
, sig
, krc
); 
 704     // get the process handle to operate on 
 705     HANDLE hProcess 
= ::OpenProcess(SYNCHRONIZE 
| 
 707                                     PROCESS_QUERY_INFORMATION
, 
 708                                     FALSE
, // not inheritable 
 710     if ( hProcess 
== NULL 
) 
 714             // recognize wxKILL_ACCESS_DENIED as special because this doesn't 
 715             // mean that the process doesn't exist and this is important for 
 716             // wxProcess::Exists() 
 717             *krc 
= ::GetLastError() == ERROR_ACCESS_DENIED
 
 718                         ? wxKILL_ACCESS_DENIED
 
 725     wxON_BLOCK_EXIT1(::CloseHandle
, hProcess
); 
 731             // kill the process forcefully returning -1 as error code 
 732             if ( !::TerminateProcess(hProcess
, (UINT
)-1) ) 
 734                 wxLogSysError(_("Failed to kill process %d"), pid
); 
 738                     // this is not supposed to happen if we could open the 
 748             // do nothing, we just want to test for process existence 
 754             // any other signal means "terminate" 
 756                 wxFindByPidParams params
; 
 757                 params
.pid 
= (DWORD
)pid
; 
 759                 // EnumWindows() has nice semantics: it returns 0 if it found 
 760                 // something or if an error occurred and non zero if it 
 761                 // enumerated all the window 
 762                 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) ) 
 764                     // did we find any window? 
 767                         // tell the app to close 
 769                         // NB: this is the harshest way, the app won't have an 
 770                         //     opportunity to save any files, for example, but 
 771                         //     this is probably what we want here. If not we 
 772                         //     can also use SendMesageTimeout(WM_CLOSE) 
 773                         if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) ) 
 775                             wxLogLastError(_T("PostMessage(WM_QUIT)")); 
 778                     else // it was an error then 
 780                         wxLogLastError(_T("EnumWindows")); 
 785                 else // no windows for this PID 
 796     DWORD rc 
wxDUMMY_INITIALIZE(0); 
 799         // as we wait for a short time, we can use just WaitForSingleObject() 
 800         // and not MsgWaitForMultipleObjects() 
 801         switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) ) 
 804                 // process terminated 
 805                 if ( !::GetExitCodeProcess(hProcess
, &rc
) ) 
 807                     wxLogLastError(_T("GetExitCodeProcess")); 
 812                 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") ); 
 816                 wxLogLastError(_T("WaitForSingleObject")); 
 829     // the return code is the same as from Unix kill(): 0 if killed 
 830     // successfully or -1 on error 
 831     if ( !ok 
|| rc 
== STILL_ACTIVE 
) 
 840 typedef HANDLE (WINAPI 
*CreateToolhelp32Snapshot_t
)(DWORD
,DWORD
); 
 841 typedef BOOL (WINAPI 
*Process32_t
)(HANDLE
,LPPROCESSENTRY32
); 
 843 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot
; 
 844 Process32_t lpfProcess32First
, lpfProcess32Next
; 
 846 static void InitToolHelp32() 
 848     static bool s_initToolHelpDone 
= false; 
 850     if (s_initToolHelpDone
) 
 853     s_initToolHelpDone 
= true; 
 855     lpfCreateToolhelp32Snapshot 
= NULL
; 
 856     lpfProcess32First 
= NULL
; 
 857     lpfProcess32Next 
= NULL
; 
 859 #if wxUSE_DYNLIB_CLASS 
 861     wxDynamicLibrary 
dllKernel(_T("kernel32.dll"), wxDL_VERBATIM
); 
 863     // Get procedure addresses. 
 864     // We are linking to these functions of Kernel32 
 865     // explicitly, because otherwise a module using 
 866     // this code would fail to load under Windows NT, 
 867     // which does not have the Toolhelp32 
 868     // functions in the Kernel 32. 
 869     lpfCreateToolhelp32Snapshot 
= 
 870         (CreateToolhelp32Snapshot_t
)dllKernel
.RawGetSymbol(_T("CreateToolhelp32Snapshot")); 
 873         (Process32_t
)dllKernel
.RawGetSymbol(_T("Process32First")); 
 876         (Process32_t
)dllKernel
.RawGetSymbol(_T("Process32Next")); 
 878 #endif // wxUSE_DYNLIB_CLASS 
 882 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError 
*krc
) 
 889     // If not implemented for this platform (e.g. NT 4.0), silently ignore 
 890     if (!lpfCreateToolhelp32Snapshot 
|| !lpfProcess32First 
|| !lpfProcess32Next
) 
 893     // Take a snapshot of all processes in the system. 
 894     HANDLE hProcessSnap 
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0); 
 895     if (hProcessSnap 
== INVALID_HANDLE_VALUE
) { 
 901     //Fill in the size of the structure before using it. 
 904     pe
.dwSize 
= sizeof(PROCESSENTRY32
); 
 906     // Walk the snapshot of the processes, and for each process, 
 907     // kill it if its parent is pid. 
 908     if (!lpfProcess32First(hProcessSnap
, &pe
)) { 
 909         // Can't get first process. 
 912         CloseHandle (hProcessSnap
); 
 917         if (pe
.th32ParentProcessID 
== (DWORD
) pid
) { 
 918             if (wxKill(pe
.th32ProcessID
, sig
, krc
)) 
 921     } while (lpfProcess32Next (hProcessSnap
, &pe
)); 
 927 // Execute a program in an Interactive Shell 
 928 bool wxShell(const wxString
& command
) 
 935     wxChar 
*shell 
= wxGetenv(wxT("COMSPEC")); 
 937         shell 
= (wxChar
*) wxT("\\COMMAND.COM"); 
 946         // pass the command to execute to the command processor 
 947         cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str()); 
 951     return wxExecute(cmd
, wxEXEC_SYNC
) == 0; 
 954 // Shutdown or reboot the PC 
 955 bool wxShutdown(wxShutdownFlags 
WXUNUSED_IN_WINCE(wFlags
)) 
 960 #elif defined(__WIN32__) 
 963     if ( wxGetOsVersion(NULL
, NULL
) == wxOS_WINDOWS_NT 
) // if is NT or 2K 
 965         // Get a token for this process. 
 967         bOK 
= ::OpenProcessToken(GetCurrentProcess(), 
 968                                  TOKEN_ADJUST_PRIVILEGES 
| TOKEN_QUERY
, 
 972             TOKEN_PRIVILEGES tkp
; 
 974             // Get the LUID for the shutdown privilege. 
 975             ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, 
 976                                    &tkp
.Privileges
[0].Luid
); 
 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
; 
 992         UINT flags 
= EWX_SHUTDOWN 
| EWX_FORCE
; 
 995             case wxSHUTDOWN_POWEROFF
: 
 996                 flags 
|= EWX_POWEROFF
; 
 999             case wxSHUTDOWN_REBOOT
: 
1000                 flags 
|= EWX_REBOOT
; 
1004                 wxFAIL_MSG( _T("unknown wxShutdown() flag") ); 
1008         bOK 
= ::ExitWindowsEx(flags
, 0) != 0; 
1015 // ---------------------------------------------------------------------------- 
1017 // ---------------------------------------------------------------------------- 
1019 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX) 
1020 wxMemorySize 
wxGetFreeMemory() 
1022 #if defined(__WIN64__) 
1023     MEMORYSTATUSEX memStatex
; 
1024     memStatex
.dwLength 
= sizeof (memStatex
); 
1025     ::GlobalMemoryStatusEx (&memStatex
); 
1026     return (wxMemorySize
)memStatex
.ullAvailPhys
; 
1027 #else /* if defined(__WIN32__) */ 
1028     MEMORYSTATUS memStatus
; 
1029     memStatus
.dwLength 
= sizeof(MEMORYSTATUS
); 
1030     ::GlobalMemoryStatus(&memStatus
); 
1031     return (wxMemorySize
)memStatus
.dwAvailPhys
; 
1035 unsigned long wxGetProcessId() 
1037     return ::GetCurrentProcessId(); 
1043     ::MessageBeep((UINT
)-1);        // default sound 
1046 bool wxIsDebuggerRunning() 
1048 #if wxUSE_DYNLIB_CLASS 
1049     // IsDebuggerPresent() is not available under Win95, so load it dynamically 
1050     wxDynamicLibrary 
dll(_T("kernel32.dll"), wxDL_VERBATIM
); 
1052     typedef BOOL (WINAPI 
*IsDebuggerPresent_t
)(); 
1053     if ( !dll
.HasSymbol(_T("IsDebuggerPresent")) ) 
1055         // no way to know, assume no 
1059     return (*(IsDebuggerPresent_t
)dll
.GetSymbol(_T("IsDebuggerPresent")))() != 0; 
1065 // ---------------------------------------------------------------------------- 
1067 // ---------------------------------------------------------------------------- 
1069 wxString 
wxGetOsDescription() 
1076     info
.dwOSVersionInfoSize 
= sizeof(OSVERSIONINFO
); 
1077     if ( ::GetVersionEx(&info
) ) 
1079         switch ( info
.dwPlatformId 
) 
1081 #ifdef VER_PLATFORM_WIN32_CE 
1082             case VER_PLATFORM_WIN32_CE
: 
1083                 str
.Printf(_("Windows CE (%d.%d)"), 
1084                            info
.dwMajorVersion
, 
1085                            info
.dwMinorVersion
); 
1088             case VER_PLATFORM_WIN32s
: 
1089                 str 
= _("Win32s on Windows 3.1"); 
1092             case VER_PLATFORM_WIN32_WINDOWS
: 
1093                 switch (info
.dwMinorVersion
) 
1096                         if ( info
.szCSDVersion
[1] == 'B' || 
1097                              info
.szCSDVersion
[1] == 'C' ) 
1099                             str 
= _("Windows 95 OSR2"); 
1103                             str 
= _("Windows 95"); 
1107                         if ( info
.szCSDVersion
[1] == 'B' || 
1108                              info
.szCSDVersion
[1] == 'C' ) 
1110                             str 
= _("Windows 98 SE"); 
1114                             str 
= _("Windows 98"); 
1118                         str 
= _("Windows ME"); 
1121                         str
.Printf(_("Windows 9x (%d.%d)"), 
1122                                    info
.dwMajorVersion
, 
1123                                    info
.dwMinorVersion
); 
1126                 if ( !wxIsEmpty(info
.szCSDVersion
) ) 
1128                     str 
<< _T(" (") << info
.szCSDVersion 
<< _T(')'); 
1132             case VER_PLATFORM_WIN32_NT
: 
1133                 if ( info
.dwMajorVersion 
== 5 ) 
1135                     switch ( info
.dwMinorVersion 
) 
1138                             str
.Printf(_("Windows 2000 (build %lu"), 
1139                                        info
.dwBuildNumber
); 
1142                             str
.Printf(_("Windows XP (build %lu"), 
1143                                        info
.dwBuildNumber
); 
1146                             str
.Printf(_("Windows Server 2003 (build %lu"), 
1147                                        info
.dwBuildNumber
); 
1153                     str
.Printf(_("Windows NT %lu.%lu (build %lu"), 
1154                            info
.dwMajorVersion
, 
1155                            info
.dwMinorVersion
, 
1156                            info
.dwBuildNumber
); 
1158                 if ( !wxIsEmpty(info
.szCSDVersion
) ) 
1160                     str 
<< _T(", ") << info
.szCSDVersion
; 
1168         wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen 
1174 bool wxIsPlatform64Bit() 
1177     return true;  // 64-bit programs run only on Win64 
1179     // 32-bit programs run on both 32-bit and 64-bit Windows so check 
1180     typedef BOOL (WINAPI 
*IsWow64Process_t
)(HANDLE
, BOOL 
*); 
1182     wxDynamicLibrary 
dllKernel32(_T("kernel32.dll")); 
1183     IsWow64Process_t pfnIsWow64Process 
= 
1184         (IsWow64Process_t
)dllKernel32
.RawGetSymbol(_T("IsWow64Process")); 
1187     if ( pfnIsWow64Process 
) 
1189         pfnIsWow64Process(::GetCurrentProcess(), &wow64
); 
1191     //else: running under a system without Win64 support 
1193     return wow64 
!= FALSE
; 
1194 #endif // Win64/Win32 
1197 wxOperatingSystemId 
wxGetOsVersion(int *verMaj
, int *verMin
) 
1202     info
.dwOSVersionInfoSize 
= sizeof(OSVERSIONINFO
); 
1203     if ( ::GetVersionEx(&info
) ) 
1205         if (verMaj
) *verMaj 
= info
.dwMajorVersion
; 
1206         if (verMin
) *verMin 
= info
.dwMinorVersion
; 
1209 #if defined( __WXWINCE__ ) 
1210     return wxOS_WINDOWS_CE
; 
1211 #elif defined( __WXMICROWIN__ ) 
1212     return wxOS_WINDOWS_MICRO
; 
1214     switch ( info
.dwPlatformId 
) 
1216     case VER_PLATFORM_WIN32_NT
: 
1217         return wxOS_WINDOWS_NT
; 
1219     case VER_PLATFORM_WIN32_WINDOWS
: 
1220         return wxOS_WINDOWS_9X
; 
1223     return wxOS_UNKNOWN
; 
1227 wxWinVersion 
wxGetWinVersion() 
1231     switch ( wxGetOsVersion(&verMaj
, &verMin
) ) 
1233         case wxOS_WINDOWS_9X
: 
1239                         return wxWinVersion_95
; 
1242                         return wxWinVersion_98
; 
1245                         return wxWinVersion_ME
; 
1250         case wxOS_WINDOWS_NT
: 
1254                     return wxWinVersion_NT3
; 
1257                     return wxWinVersion_NT4
; 
1263                             return wxWinVersion_2000
; 
1266                             return wxWinVersion_XP
; 
1269                             return wxWinVersion_2003
; 
1274                     return wxWinVersion_NT6
; 
1279             // Do nothing just to silence GCC warning 
1283     return wxWinVersion_Unknown
; 
1286 // ---------------------------------------------------------------------------- 
1288 // ---------------------------------------------------------------------------- 
1290 void wxMilliSleep(unsigned long milliseconds
) 
1292     ::Sleep(milliseconds
); 
1295 void wxMicroSleep(unsigned long microseconds
) 
1297     wxMilliSleep(microseconds
/1000); 
1300 void wxSleep(int nSecs
) 
1302     wxMilliSleep(1000*nSecs
); 
1305 // ---------------------------------------------------------------------------- 
1306 // font encoding <-> Win32 codepage conversion functions 
1307 // ---------------------------------------------------------------------------- 
1309 extern WXDLLIMPEXP_BASE 
long wxEncodingToCharset(wxFontEncoding encoding
) 
1313         // although this function is supposed to return an exact match, do do 
1314         // some mappings here for the most common case of "standard" encoding 
1315         case wxFONTENCODING_SYSTEM
: 
1316             return DEFAULT_CHARSET
; 
1318         case wxFONTENCODING_ISO8859_1
: 
1319         case wxFONTENCODING_ISO8859_15
: 
1320         case wxFONTENCODING_CP1252
: 
1321             return ANSI_CHARSET
; 
1323 #if !defined(__WXMICROWIN__) 
1324         // The following four fonts are multi-byte charsets 
1325         case wxFONTENCODING_CP932
: 
1326             return SHIFTJIS_CHARSET
; 
1328         case wxFONTENCODING_CP936
: 
1329             return GB2312_CHARSET
; 
1332         case wxFONTENCODING_CP949
: 
1333             return HANGUL_CHARSET
; 
1336         case wxFONTENCODING_CP950
: 
1337             return CHINESEBIG5_CHARSET
; 
1339         // The rest are single byte encodings 
1340         case wxFONTENCODING_CP1250
: 
1341             return EASTEUROPE_CHARSET
; 
1343         case wxFONTENCODING_CP1251
: 
1344             return RUSSIAN_CHARSET
; 
1346         case wxFONTENCODING_CP1253
: 
1347             return GREEK_CHARSET
; 
1349         case wxFONTENCODING_CP1254
: 
1350             return TURKISH_CHARSET
; 
1352         case wxFONTENCODING_CP1255
: 
1353             return HEBREW_CHARSET
; 
1355         case wxFONTENCODING_CP1256
: 
1356             return ARABIC_CHARSET
; 
1358         case wxFONTENCODING_CP1257
: 
1359             return BALTIC_CHARSET
; 
1361         case wxFONTENCODING_CP874
: 
1362             return THAI_CHARSET
; 
1363 #endif // !__WXMICROWIN__ 
1365         case wxFONTENCODING_CP437
: 
1369             // no way to translate this encoding into a Windows charset 
1374 // we have 2 versions of wxCharsetToCodepage(): the old one which directly 
1375 // looks up the vlaues in the registry and the new one which is more 
1376 // politically correct and has more chances to work on other Windows versions 
1377 // as well but the old version is still needed for !wxUSE_FONTMAP case 
1380 #include "wx/fontmap.h" 
1382 extern WXDLLIMPEXP_BASE 
long wxEncodingToCodepage(wxFontEncoding encoding
) 
1384     // There don't seem to be symbolic names for 
1385     // these under Windows so I just copied the 
1386     // values from MSDN. 
1392         case wxFONTENCODING_ISO8859_1
:      ret 
= 28591; break; 
1393         case wxFONTENCODING_ISO8859_2
:      ret 
= 28592; break; 
1394         case wxFONTENCODING_ISO8859_3
:      ret 
= 28593; break; 
1395         case wxFONTENCODING_ISO8859_4
:      ret 
= 28594; break; 
1396         case wxFONTENCODING_ISO8859_5
:      ret 
= 28595; break; 
1397         case wxFONTENCODING_ISO8859_6
:      ret 
= 28596; break; 
1398         case wxFONTENCODING_ISO8859_7
:      ret 
= 28597; break; 
1399         case wxFONTENCODING_ISO8859_8
:      ret 
= 28598; break; 
1400         case wxFONTENCODING_ISO8859_9
:      ret 
= 28599; break; 
1401         case wxFONTENCODING_ISO8859_10
:     ret 
= 28600; break; 
1402         case wxFONTENCODING_ISO8859_11
:     ret 
= 874; break; 
1403         // case wxFONTENCODING_ISO8859_12,      // doesn't exist currently, but put it 
1404         case wxFONTENCODING_ISO8859_13
:     ret 
= 28603; break; 
1405         // case wxFONTENCODING_ISO8859_14:     ret = 28604; break; // no correspondence on Windows 
1406         case wxFONTENCODING_ISO8859_15
:     ret 
= 28605; break; 
1407         case wxFONTENCODING_KOI8
:           ret 
= 20866; break; 
1408         case wxFONTENCODING_KOI8_U
:         ret 
= 21866; break; 
1409         case wxFONTENCODING_CP437
:          ret 
= 437; break; 
1410         case wxFONTENCODING_CP850
:          ret 
= 850; break; 
1411         case wxFONTENCODING_CP852
:          ret 
= 852; break; 
1412         case wxFONTENCODING_CP855
:          ret 
= 855; break; 
1413         case wxFONTENCODING_CP866
:          ret 
= 866; break; 
1414         case wxFONTENCODING_CP874
:          ret 
= 874; break; 
1415         case wxFONTENCODING_CP932
:          ret 
= 932; break; 
1416         case wxFONTENCODING_CP936
:          ret 
= 936; break; 
1417         case wxFONTENCODING_CP949
:          ret 
= 949; break; 
1418         case wxFONTENCODING_CP950
:          ret 
= 950; break; 
1419         case wxFONTENCODING_CP1250
:         ret 
= 1250; break; 
1420         case wxFONTENCODING_CP1251
:         ret 
= 1251; break; 
1421         case wxFONTENCODING_CP1252
:         ret 
= 1252; break; 
1422         case wxFONTENCODING_CP1253
:         ret 
= 1253; break; 
1423         case wxFONTENCODING_CP1254
:         ret 
= 1254; break; 
1424         case wxFONTENCODING_CP1255
:         ret 
= 1255; break; 
1425         case wxFONTENCODING_CP1256
:         ret 
= 1256; break; 
1426         case wxFONTENCODING_CP1257
:         ret 
= 1257; break; 
1427         case wxFONTENCODING_EUC_JP
:         ret 
= 20932; break; 
1428         case wxFONTENCODING_MACROMAN
:       ret 
= 10000; break; 
1429         case wxFONTENCODING_MACJAPANESE
:    ret 
= 10001; break; 
1430         case wxFONTENCODING_MACCHINESETRAD
: ret 
= 10002; break; 
1431         case wxFONTENCODING_MACKOREAN
:      ret 
= 10003; break; 
1432         case wxFONTENCODING_MACARABIC
:      ret 
= 10004; break; 
1433         case wxFONTENCODING_MACHEBREW
:      ret 
= 10005; break; 
1434         case wxFONTENCODING_MACGREEK
:       ret 
= 10006; break; 
1435         case wxFONTENCODING_MACCYRILLIC
:    ret 
= 10007; break; 
1436         case wxFONTENCODING_MACTHAI
:        ret 
= 10021; break; 
1437         case wxFONTENCODING_MACCHINESESIMP
: ret 
= 10008; break; 
1438         case wxFONTENCODING_MACCENTRALEUR
:  ret 
= 10029; break; 
1439         case wxFONTENCODING_MACCROATIAN
:    ret 
= 10082; break; 
1440         case wxFONTENCODING_MACICELANDIC
:   ret 
= 10079; break; 
1441         case wxFONTENCODING_MACROMANIAN
:    ret 
= 10009; break; 
1442         case wxFONTENCODING_UTF7
:           ret 
= 65000; break; 
1443         case wxFONTENCODING_UTF8
:           ret 
= 65001; break; 
1447     if (::IsValidCodePage(ret
) == 0) 
1451     if (::GetCPInfo(ret
, &info
) == 0) 
1457 extern long wxCharsetToCodepage(const char *name
) 
1459     // first get the font encoding for this charset 
1463     wxFontEncoding enc 
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false); 
1464     if ( enc 
== wxFONTENCODING_SYSTEM 
) 
1467     // the use the helper function 
1468     return wxEncodingToCodepage(enc
); 
1471 #else // !wxUSE_FONTMAP 
1473 #include "wx/msw/registry.h" 
1475 // this should work if Internet Exploiter is installed 
1476 extern long wxCharsetToCodepage(const char *name
) 
1483     wxString 
path(wxT("MIME\\Database\\Charset\\")); 
1486     // follow the alias loop 
1489         wxRegKey 
key(wxRegKey::HKCR
, path 
+ cn
); 
1494         // two cases: either there's an AliasForCharset string, 
1495         // or there are Codepage and InternetEncoding dwords. 
1496         // The InternetEncoding gives us the actual encoding, 
1497         // the Codepage just says which Windows character set to 
1498         // use when displaying the data. 
1499         if (key
.HasValue(wxT("InternetEncoding")) && 
1500             key
.QueryValue(wxT("InternetEncoding"), &CP
)) 
1503         // no encoding, see if it's an alias 
1504         if (!key
.HasValue(wxT("AliasForCharset")) || 
1505             !key
.QueryValue(wxT("AliasForCharset"), cn
)) 
1512 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP 
1515   Creates a hidden window with supplied window proc registering the class for 
1516   it if necesssary (i.e. the first time only). Caller is responsible for 
1517   destroying the window and unregistering the class (note that this must be 
1518   done because wxWidgets may be used as a DLL and so may be loaded/unloaded 
1519   multiple times into/from the same process so we cna't rely on automatic 
1520   Windows class unregistration). 
1522   pclassname is a pointer to a caller stored classname, which must initially be 
1523   NULL. classname is the desired wndclass classname. If function successfully 
1524   registers the class, pclassname will be set to classname. 
1526 extern "C" WXDLLIMPEXP_BASE HWND
 
1527 wxCreateHiddenWindow(LPCTSTR 
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
) 
1529     wxCHECK_MSG( classname 
&& pclassname 
&& wndproc
, NULL
, 
1530                     _T("NULL parameter in wxCreateHiddenWindow") ); 
1532     // register the class fi we need to first 
1533     if ( *pclassname 
== NULL 
) 
1536         wxZeroMemory(wndclass
); 
1538         wndclass
.lpfnWndProc   
= wndproc
; 
1539         wndclass
.hInstance     
= wxGetInstance(); 
1540         wndclass
.lpszClassName 
= classname
; 
1542         if ( !::RegisterClass(&wndclass
) ) 
1544             wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow")); 
1549         *pclassname 
= classname
; 
1552     // next create the window 
1553     HWND hwnd 
= ::CreateWindow
 
1567         wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));