1 /////////////////////////////////////////////////////////////////////////////
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/apptrait.h"
35 #include "wx/dynlib.h"
36 #include "wx/dynload.h"
38 #include "wx/confbase.h" // for wxExpandEnvVars()
40 #include "wx/msw/private.h" // includes <windows.h>
41 #include "wx/msw/missing.h" // CHARSET_HANGUL
43 // Doesn't work with Cygwin at present
44 #if wxUSE_SOCKETS && (defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) || defined(__CYGWIN32__))
45 // apparently we need to include winsock.h to get WSADATA and other stuff
46 // used in wxGetFullHostName() with the old mingw32 versions
52 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
60 #if defined(__CYGWIN__)
61 #include <sys/unistd.h>
63 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
66 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
67 // this (3.1 I believe) and how to test for it.
68 // If this works for Borland 4.0 as well, then no worries.
72 // VZ: there is some code using NetXXX() functions to get the full user name:
73 // I don't think it's a good idea because they don't work under Win95 and
74 // seem to return the same as wxGetUserId() under NT. If you really want
75 // to use them, just #define USE_NET_API
82 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
93 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
98 // For wxKillAllChildren
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 // In the WIN.INI file
106 static const wxChar WX_SECTION
[] = wxT("wxWindows");
107 static const wxChar eUSERNAME
[] = wxT("UserName");
109 // ============================================================================
111 // ============================================================================
113 // ----------------------------------------------------------------------------
114 // get host name and related
115 // ----------------------------------------------------------------------------
117 // Get hostname only (without domain name)
118 bool wxGetHostName(wxChar
*buf
, int maxSize
)
120 #if defined(__WXWINCE__)
123 wxUnusedVar(maxSize
);
125 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
126 DWORD nSize
= maxSize
;
127 if ( !::GetComputerName(buf
, &nSize
) )
129 wxLogLastError(wxT("GetComputerName"));
137 const wxChar
*default_host
= wxT("noname");
139 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
140 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
142 wxStrncpy(buf
, sysname
, maxSize
- 1);
143 buf
[maxSize
] = wxT('\0');
144 return *buf
? true : false;
148 // get full hostname (with domain name if possible)
149 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
151 #if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER && wxUSE_SOCKETS
152 // TODO should use GetComputerNameEx() when available
154 // we don't want to always link with Winsock DLL as we might not use it at
155 // all, so load it dynamically here if needed (and don't complain if it is
156 // missing, we handle this)
159 wxDynamicLibrary
dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM
);
160 if ( dllWinsock
.IsLoaded() )
162 typedef int (PASCAL
*WSAStartup_t
)(WORD
, WSADATA
*);
163 typedef int (PASCAL
*gethostname_t
)(char *, int);
164 typedef hostent
* (PASCAL
*gethostbyname_t
)(const char *);
165 typedef hostent
* (PASCAL
*gethostbyaddr_t
)(const char *, int , int);
166 typedef int (PASCAL
*WSACleanup_t
)(void);
168 #define LOAD_WINSOCK_FUNC(func) \
170 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
172 LOAD_WINSOCK_FUNC(WSAStartup
);
175 if ( pfnWSAStartup
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
177 LOAD_WINSOCK_FUNC(gethostname
);
180 if ( pfngethostname
)
183 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
185 // gethostname() won't usually include the DNS domain name,
186 // for this we need to work a bit more
187 if ( !strchr(bufA
, '.') )
189 LOAD_WINSOCK_FUNC(gethostbyname
);
191 struct hostent
*pHostEnt
= pfngethostbyname
192 ? pfngethostbyname(bufA
)
197 // Windows will use DNS internally now
198 LOAD_WINSOCK_FUNC(gethostbyaddr
);
200 pHostEnt
= pfngethostbyaddr
201 ? pfngethostbyaddr(pHostEnt
->h_addr
,
208 host
= wxString::FromAscii(pHostEnt
->h_name
);
214 LOAD_WINSOCK_FUNC(WSACleanup
);
221 wxStrncpy(buf
, host
, maxSize
);
227 #endif // !__WXMICROWIN__
229 return wxGetHostName(buf
, maxSize
);
232 // Get user ID e.g. jacs
233 bool wxGetUserId(wxChar
*buf
, int maxSize
)
235 #if defined(__WXWINCE__)
238 wxUnusedVar(maxSize
);
240 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
241 DWORD nSize
= maxSize
;
242 if ( ::GetUserName(buf
, &nSize
) == 0 )
244 // actually, it does happen on Win9x if the user didn't log on
245 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
254 #else // __WXMICROWIN__
256 const wxChar
*default_id
= wxT("anonymous");
258 // Can't assume we have NIS (PC-NFS) or some other ID daemon
260 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
261 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
263 // Use wxWidgets configuration data (comming soon)
264 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
268 wxStrncpy(buf
, user
, maxSize
- 1);
271 return *buf
? true : false;
275 // Get user name e.g. Julian Smart
276 bool wxGetUserName(wxChar
*buf
, int maxSize
)
278 #if defined(__WXWINCE__)
281 wxUnusedVar(maxSize
);
283 #elif defined(USE_NET_API)
284 CHAR szUserName
[256];
285 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
288 // TODO how to get the domain name?
291 // the code is based on the MSDN example (also see KB article Q119670)
292 WCHAR wszUserName
[256]; // Unicode user name
293 WCHAR wszDomain
[256];
296 USER_INFO_2
*ui2
; // User structure
298 // Convert ANSI user name and domain to Unicode
299 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
300 wszUserName
, WXSIZEOF(wszUserName
) );
301 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
302 wszDomain
, WXSIZEOF(wszDomain
) );
304 // Get the computer name of a DC for the domain.
305 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
307 wxLogError(wxT("Can not find domain controller"));
312 // Look up the user on the DC
313 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
314 (LPWSTR
)&wszUserName
,
315 2, // level - we want USER_INFO_2
323 case NERR_InvalidComputer
:
324 wxLogError(wxT("Invalid domain controller name."));
328 case NERR_UserNotFound
:
329 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
334 wxLogSysError(wxT("Can't get information about user"));
339 // Convert the Unicode full name to ANSI
340 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
341 buf
, maxSize
, NULL
, NULL
);
346 wxLogError(wxT("Couldn't look up full user name."));
349 #else // !USE_NET_API
350 // Could use NIS, MS-Mail or other site specific programs
351 // Use wxWidgets configuration data
352 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize
- 1) != 0;
355 ok
= wxGetUserId(buf
, maxSize
);
360 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
367 const wxChar
* wxGetHomeDir(wxString
*pstr
)
369 wxString
& strDir
= *pstr
;
371 // first branch is for Cygwin
372 #if defined(__UNIX__)
373 const wxChar
*szHome
= wxGetenv("HOME");
374 if ( szHome
== NULL
) {
376 wxLogWarning(_("can't find user's HOME, using current directory."));
382 // add a trailing slash if needed
383 if ( strDir
.Last() != wxT('/') )
387 // Cygwin returns unix type path but that does not work well
388 static wxChar windowsPath
[MAX_PATH
];
389 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
390 strDir
= windowsPath
;
392 #elif defined(__WXWINCE__)
397 // If we have a valid HOME directory, as is used on many machines that
398 // have unix utilities on them, we should use that.
399 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
401 if ( szHome
!= NULL
)
405 else // no HOME, try HOMEDRIVE/PATH
407 szHome
= wxGetenv(wxT("HOMEDRIVE"));
408 if ( szHome
!= NULL
)
410 szHome
= wxGetenv(wxT("HOMEPATH"));
412 if ( szHome
!= NULL
)
416 // the idea is that under NT these variables have default values
417 // of "%systemdrive%:" and "\\". As we don't want to create our
418 // config files in the root directory of the system drive, we will
419 // create it in our program's dir. However, if the user took care
420 // to set HOMEPATH to something other than "\\", we suppose that he
421 // knows what he is doing and use the supplied value.
422 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
427 if ( strDir
.empty() )
429 // If we have a valid USERPROFILE directory, as is the case in
430 // Windows NT, 2000 and XP, we should use that as our home directory.
431 szHome
= wxGetenv(wxT("USERPROFILE"));
433 if ( szHome
!= NULL
)
437 if ( !strDir
.empty() )
439 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
440 // value once again, it shouldn't hurt anyhow
441 strDir
= wxExpandEnvVars(strDir
);
443 else // fall back to the program directory
445 // extract the directory component of the program file name
446 wxSplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
450 return strDir
.c_str();
453 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
455 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
456 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
457 // static buffer and sometimes I don't even know what.
458 static wxString s_home
;
460 return (wxChar
*)wxGetHomeDir(&s_home
);
463 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
475 // old w32api don't have ULARGE_INTEGER
476 #if defined(__WIN32__) && \
477 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
478 // GetDiskFreeSpaceEx() is not available under original Win95, check for
480 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
486 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
488 ::GetModuleHandle(_T("kernel32.dll")),
490 "GetDiskFreeSpaceExW"
492 "GetDiskFreeSpaceExA"
496 if ( pGetDiskFreeSpaceEx
)
498 ULARGE_INTEGER bytesFree
, bytesTotal
;
500 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
501 if ( !pGetDiskFreeSpaceEx(path
,
506 wxLogLastError(_T("GetDiskFreeSpaceEx"));
511 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
512 // two 32 bit fields which may be or may be not named - try to make it
513 // compile in all cases
514 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
521 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
526 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
532 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
533 // should be used instead - but if it's not available, fall back on
534 // GetDiskFreeSpace() nevertheless...
536 DWORD lSectorsPerCluster
,
538 lNumberOfFreeClusters
,
539 lTotalNumberOfClusters
;
541 // FIXME: this is wrong, we should extract the root drive from path
542 // instead, but this is the job for wxFileName...
543 if ( !::GetDiskFreeSpace(path
,
546 &lNumberOfFreeClusters
,
547 &lTotalNumberOfClusters
) )
549 wxLogLastError(_T("GetDiskFreeSpace"));
554 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
555 lBytesPerCluster
*= lBytesPerSector
;
559 *pTotal
= lBytesPerCluster
;
560 *pTotal
*= lTotalNumberOfClusters
;
565 *pFree
= lBytesPerCluster
;
566 *pFree
*= lNumberOfFreeClusters
;
575 // ----------------------------------------------------------------------------
577 // ----------------------------------------------------------------------------
579 bool wxGetEnv(const wxString
& var
, wxString
*value
)
582 // no environment variables under CE
587 // first get the size of the buffer
588 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
591 // this means that there is no such variable
597 (void)::GetEnvironmentVariable(var
, wxStringBuffer(*value
, dwRet
),
605 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
607 // some compilers have putenv() or _putenv() or _wputenv() but it's better
608 // to always use Win32 function directly instead of dealing with them
609 #if defined(__WIN32__) && !defined(__WXWINCE__)
610 if ( !::SetEnvironmentVariable(var
, value
) )
612 wxLogLastError(_T("SetEnvironmentVariable"));
618 #else // no way to set env vars
619 // no environment variables under CE
626 // ----------------------------------------------------------------------------
627 // process management
628 // ----------------------------------------------------------------------------
630 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
631 struct wxFindByPidParams
633 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
635 // the HWND used to return the result
638 // the PID we're looking from
641 DECLARE_NO_COPY_CLASS(wxFindByPidParams
)
644 // wxKill helper: EnumWindows() callback which is used to find the first (top
645 // level) window belonging to the given process
646 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
649 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
651 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
652 if ( pid
== params
->pid
)
654 // remember the window we found
657 // return FALSE to stop the enumeration
661 // continue enumeration
665 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
);
667 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
, int flags
)
669 if (flags
& wxKILL_CHILDREN
)
670 wxKillAllChildren(pid
, sig
, krc
);
672 // get the process handle to operate on
673 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
675 PROCESS_QUERY_INFORMATION
,
676 FALSE
, // not inheritable
678 if ( hProcess
== NULL
)
682 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
684 *krc
= wxKILL_ACCESS_DENIED
;
688 *krc
= wxKILL_NO_PROCESS
;
699 // kill the process forcefully returning -1 as error code
700 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
702 wxLogSysError(_("Failed to kill process %d"), pid
);
706 // this is not supposed to happen if we could open the
716 // do nothing, we just want to test for process existence
720 // any other signal means "terminate"
722 wxFindByPidParams params
;
723 params
.pid
= (DWORD
)pid
;
725 // EnumWindows() has nice semantics: it returns 0 if it found
726 // something or if an error occured and non zero if it
727 // enumerated all the window
728 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
730 // did we find any window?
733 // tell the app to close
735 // NB: this is the harshest way, the app won't have
736 // opportunity to save any files, for example, but
737 // this is probably what we want here. If not we
738 // can also use SendMesageTimeout(WM_CLOSE)
739 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
741 wxLogLastError(_T("PostMessage(WM_QUIT)"));
744 else // it was an error then
746 wxLogLastError(_T("EnumWindows"));
751 else // no windows for this PID
768 // as we wait for a short time, we can use just WaitForSingleObject()
769 // and not MsgWaitForMultipleObjects()
770 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
773 // process terminated
774 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
776 wxLogLastError(_T("GetExitCodeProcess"));
781 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
785 wxLogLastError(_T("WaitForSingleObject"));
800 // just to suppress the warnings about uninitialized variable
804 ::CloseHandle(hProcess
);
806 // the return code is the same as from Unix kill(): 0 if killed
807 // successfully or -1 on error
809 // be careful to interpret rc correctly: for wxSIGNONE we return success if
810 // the process exists, for all the other sig values -- if it doesn't
812 ((sig
== wxSIGNONE
) == (rc
== STILL_ACTIVE
)) )
826 HANDLE (WINAPI
*lpfCreateToolhelp32Snapshot
)(DWORD
,DWORD
) ;
827 BOOL (WINAPI
*lpfProcess32First
)(HANDLE
,LPPROCESSENTRY32
) ;
828 BOOL (WINAPI
*lpfProcess32Next
)(HANDLE
,LPPROCESSENTRY32
) ;
830 static void InitToolHelp32()
832 static bool s_initToolHelpDone
= false;
834 if (s_initToolHelpDone
)
837 s_initToolHelpDone
= true;
839 lpfCreateToolhelp32Snapshot
= NULL
;
840 lpfProcess32First
= NULL
;
841 lpfProcess32Next
= NULL
;
843 HINSTANCE hInstLib
= LoadLibrary( wxT("Kernel32.DLL") ) ;
844 if( hInstLib
== NULL
)
847 // Get procedure addresses.
848 // We are linking to these functions of Kernel32
849 // explicitly, because otherwise a module using
850 // this code would fail to load under Windows NT,
851 // which does not have the Toolhelp32
852 // functions in the Kernel 32.
853 lpfCreateToolhelp32Snapshot
=
854 (HANDLE(WINAPI
*)(DWORD
,DWORD
))
855 GetProcAddress( hInstLib
,
857 wxT("CreateToolhelp32Snapshot")
859 "CreateToolhelp32Snapshot"
864 (BOOL(WINAPI
*)(HANDLE
,LPPROCESSENTRY32
))
865 GetProcAddress( hInstLib
,
867 wxT("Process32First")
874 (BOOL(WINAPI
*)(HANDLE
,LPPROCESSENTRY32
))
875 GetProcAddress( hInstLib
,
883 FreeLibrary( hInstLib
) ;
887 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
)
894 // If not implemented for this platform (e.g. NT 4.0), silently ignore
895 if (!lpfCreateToolhelp32Snapshot
|| !lpfProcess32First
|| !lpfProcess32Next
)
898 // Take a snapshot of all processes in the system.
899 HANDLE hProcessSnap
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
900 if (hProcessSnap
== INVALID_HANDLE_VALUE
) {
906 //Fill in the size of the structure before using it.
909 pe
.dwSize
= sizeof(PROCESSENTRY32
);
911 // Walk the snapshot of the processes, and for each process,
912 // kill it if its parent is pid.
913 if (!lpfProcess32First(hProcessSnap
, &pe
)) {
914 // Can't get first process.
917 CloseHandle (hProcessSnap
);
922 if (pe
.th32ParentProcessID
== (DWORD
) pid
) {
923 if (wxKill(pe
.th32ProcessID
, sig
, krc
))
926 } while (lpfProcess32Next (hProcessSnap
, &pe
));
932 // Execute a program in an Interactive Shell
933 bool wxShell(const wxString
& command
)
940 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
942 shell
= (wxChar
*) wxT("\\COMMAND.COM");
951 // pass the command to execute to the command processor
952 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
956 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
959 // Shutdown or reboot the PC
960 bool wxShutdown(wxShutdownFlags wFlags
)
966 #elif defined(__WIN32__)
969 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT
) // if is NT or 2K
971 // Get a token for this process.
973 bOK
= ::OpenProcessToken(GetCurrentProcess(),
974 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
978 TOKEN_PRIVILEGES tkp
;
980 // Get the LUID for the shutdown privilege.
981 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
982 &tkp
.Privileges
[0].Luid
);
984 tkp
.PrivilegeCount
= 1; // one privilege to set
985 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
987 // Get the shutdown privilege for this process.
988 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
989 (PTOKEN_PRIVILEGES
)NULL
, 0);
991 // Cannot test the return value of AdjustTokenPrivileges.
992 bOK
= ::GetLastError() == ERROR_SUCCESS
;
998 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
1001 case wxSHUTDOWN_POWEROFF
:
1002 flags
|= EWX_POWEROFF
;
1005 case wxSHUTDOWN_REBOOT
:
1006 flags
|= EWX_REBOOT
;
1010 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
1014 bOK
= ::ExitWindowsEx(flags
, 0) != 0;
1021 wxPowerType
wxGetPowerType()
1024 return wxPOWER_UNKNOWN
;
1027 wxBatteryState
wxGetBatteryState()
1030 return wxBATTERY_UNKNOWN_STATE
;
1033 // ----------------------------------------------------------------------------
1035 // ----------------------------------------------------------------------------
1037 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1038 wxMemorySize
wxGetFreeMemory()
1040 #if defined(__WIN64__)
1041 MEMORYSTATUSEX memStatex
;
1042 statex
.dwLength
= sizeof (statex
);
1043 ::GlobalMemoryStatusEx (&statex
);
1044 return (wxMemorySize
)memStatus
.ullAvailPhys
;
1045 #else /* if defined(__WIN32__) */
1046 MEMORYSTATUS memStatus
;
1047 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1048 ::GlobalMemoryStatus(&memStatus
);
1049 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1053 unsigned long wxGetProcessId()
1055 return ::GetCurrentProcessId();
1061 ::MessageBeep((UINT
)-1); // default sound
1064 bool wxIsDebuggerRunning()
1066 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1067 wxDynamicLibrary
dll(_T("kernel32.dll"), wxDL_VERBATIM
);
1069 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1070 if ( !dll
.HasSymbol(_T("IsDebuggerPresent")) )
1072 // no way to know, assume no
1076 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(_T("IsDebuggerPresent")))() != 0;
1079 // ----------------------------------------------------------------------------
1081 // ----------------------------------------------------------------------------
1083 wxString
wxGetOsDescription()
1090 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1091 if ( ::GetVersionEx(&info
) )
1093 switch ( info
.dwPlatformId
)
1095 case VER_PLATFORM_WIN32s
:
1096 str
= _("Win32s on Windows 3.1");
1099 case VER_PLATFORM_WIN32_WINDOWS
:
1100 switch (info
.dwMinorVersion
)
1103 if ( info
.szCSDVersion
[1] == 'B' ||
1104 info
.szCSDVersion
[1] == 'C' )
1106 str
= _("Windows 95 OSR2");
1110 str
= _("Windows 95");
1114 if ( info
.szCSDVersion
[1] == 'B' ||
1115 info
.szCSDVersion
[1] == 'C' )
1117 str
= _("Windows 98 SE");
1121 str
= _("Windows 98");
1125 str
= _("Windows ME");
1128 str
.Printf(_("Windows 9x (%d.%d)"),
1129 info
.dwMajorVersion
,
1130 info
.dwMinorVersion
);
1133 if ( !wxIsEmpty(info
.szCSDVersion
) )
1135 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
1139 case VER_PLATFORM_WIN32_NT
:
1140 if ( info
.dwMajorVersion
== 5 )
1142 switch ( info
.dwMinorVersion
)
1145 str
.Printf(_("Windows 2000 (build %lu"),
1146 info
.dwBuildNumber
);
1149 str
.Printf(_("Windows XP (build %lu"),
1150 info
.dwBuildNumber
);
1153 str
.Printf(_("Windows Server 2003 (build %lu"),
1154 info
.dwBuildNumber
);
1158 if ( wxIsEmpty(str
) )
1160 str
.Printf(_("Windows NT %lu.%lu (build %lu"),
1161 info
.dwMajorVersion
,
1162 info
.dwMinorVersion
,
1163 info
.dwBuildNumber
);
1165 if ( !wxIsEmpty(info
.szCSDVersion
) )
1167 str
<< _T(", ") << info
.szCSDVersion
;
1175 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1181 wxToolkitInfo
& wxAppTraits::GetToolkitInfo()
1183 // cache the version info, it's not going to change
1185 // NB: this is MT-safe, we may use these static vars from different threads
1186 // but as they always have the same value it doesn't matter
1187 static int s_ver
= -1,
1197 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1198 if ( ::GetVersionEx(&info
) )
1200 s_major
= info
.dwMajorVersion
;
1201 s_minor
= info
.dwMinorVersion
;
1203 #ifdef __SMARTPHONE__
1204 s_ver
= wxWINDOWS_SMARTPHONE
;
1205 #elif defined(__POCKETPC__)
1206 s_ver
= wxWINDOWS_POCKETPC
;
1208 switch ( info
.dwPlatformId
)
1210 case VER_PLATFORM_WIN32s
:
1214 case VER_PLATFORM_WIN32_WINDOWS
:
1218 case VER_PLATFORM_WIN32_NT
:
1219 s_ver
= wxWINDOWS_NT
;
1222 case VER_PLATFORM_WIN32_CE
:
1223 s_ver
= wxWINDOWS_CE
;
1230 static wxToolkitInfo info
;
1231 info
.versionMajor
= s_major
;
1232 info
.versionMinor
= s_minor
;
1234 info
.name
= _T("wxBase");
1238 // ----------------------------------------------------------------------------
1240 // ----------------------------------------------------------------------------
1242 void wxMilliSleep(unsigned long milliseconds
)
1244 ::Sleep(milliseconds
);
1247 void wxMicroSleep(unsigned long microseconds
)
1249 wxMilliSleep(microseconds
/1000);
1252 void wxSleep(int nSecs
)
1254 wxMilliSleep(1000*nSecs
);
1257 // ----------------------------------------------------------------------------
1258 // font encoding <-> Win32 codepage conversion functions
1259 // ----------------------------------------------------------------------------
1261 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1265 // although this function is supposed to return an exact match, do do
1266 // some mappings here for the most common case of "standard" encoding
1267 case wxFONTENCODING_SYSTEM
:
1268 return DEFAULT_CHARSET
;
1270 case wxFONTENCODING_ISO8859_1
:
1271 case wxFONTENCODING_ISO8859_15
:
1272 case wxFONTENCODING_CP1252
:
1273 return ANSI_CHARSET
;
1275 #if !defined(__WXMICROWIN__)
1276 // The following four fonts are multi-byte charsets
1277 case wxFONTENCODING_CP932
:
1278 return SHIFTJIS_CHARSET
;
1280 case wxFONTENCODING_CP936
:
1281 return GB2312_CHARSET
;
1283 case wxFONTENCODING_CP949
:
1284 return HANGUL_CHARSET
;
1286 case wxFONTENCODING_CP950
:
1287 return CHINESEBIG5_CHARSET
;
1289 // The rest are single byte encodings
1290 case wxFONTENCODING_CP1250
:
1291 return EASTEUROPE_CHARSET
;
1293 case wxFONTENCODING_CP1251
:
1294 return RUSSIAN_CHARSET
;
1296 case wxFONTENCODING_CP1253
:
1297 return GREEK_CHARSET
;
1299 case wxFONTENCODING_CP1254
:
1300 return TURKISH_CHARSET
;
1302 case wxFONTENCODING_CP1255
:
1303 return HEBREW_CHARSET
;
1305 case wxFONTENCODING_CP1256
:
1306 return ARABIC_CHARSET
;
1308 case wxFONTENCODING_CP1257
:
1309 return BALTIC_CHARSET
;
1311 case wxFONTENCODING_CP874
:
1312 return THAI_CHARSET
;
1313 #endif // !__WXMICROWIN__
1315 case wxFONTENCODING_CP437
:
1319 // no way to translate this encoding into a Windows charset
1324 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1325 // looks up the vlaues in the registry and the new one which is more
1326 // politically correct and has more chances to work on other Windows versions
1327 // as well but the old version is still needed for !wxUSE_FONTMAP case
1330 #include "wx/fontmap.h"
1332 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1334 // There don't seem to be symbolic names for
1335 // these under Windows so I just copied the
1336 // values from MSDN.
1342 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1343 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1344 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1345 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1346 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1347 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1348 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1349 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1350 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1351 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1352 case wxFONTENCODING_ISO8859_11
: ret
= 28601; break;
1353 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1354 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1355 case wxFONTENCODING_ISO8859_14
: ret
= 28604; break;
1356 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1357 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1358 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1359 case wxFONTENCODING_CP437
: ret
= 437; break;
1360 case wxFONTENCODING_CP850
: ret
= 850; break;
1361 case wxFONTENCODING_CP852
: ret
= 852; break;
1362 case wxFONTENCODING_CP855
: ret
= 855; break;
1363 case wxFONTENCODING_CP866
: ret
= 866; break;
1364 case wxFONTENCODING_CP874
: ret
= 874; break;
1365 case wxFONTENCODING_CP932
: ret
= 932; break;
1366 case wxFONTENCODING_CP936
: ret
= 936; break;
1367 case wxFONTENCODING_CP949
: ret
= 949; break;
1368 case wxFONTENCODING_CP950
: ret
= 950; break;
1369 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1370 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1371 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1372 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1373 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1374 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1375 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1376 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1377 case wxFONTENCODING_EUC_JP
: ret
= 51932; break;
1378 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1379 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1380 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1381 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1382 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1383 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1384 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1385 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1386 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1387 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1388 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1389 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1390 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1391 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1392 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1393 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1397 if (::IsValidCodePage(ret
) == 0)
1401 if (::GetCPInfo(ret
, &info
) == 0)
1407 extern long wxCharsetToCodepage(const wxChar
*name
)
1409 // first get the font encoding for this charset
1413 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(name
, false);
1414 if ( enc
== wxFONTENCODING_SYSTEM
)
1417 // the use the helper function
1418 return wxEncodingToCodepage(enc
);
1421 #else // !wxUSE_FONTMAP
1423 #include "wx/msw/registry.h"
1425 // this should work if Internet Exploiter is installed
1426 extern long wxCharsetToCodepage(const wxChar
*name
)
1433 wxString
path(wxT("MIME\\Database\\Charset\\"));
1436 // follow the alias loop
1439 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1444 // two cases: either there's an AliasForCharset string,
1445 // or there are Codepage and InternetEncoding dwords.
1446 // The InternetEncoding gives us the actual encoding,
1447 // the Codepage just says which Windows character set to
1448 // use when displaying the data.
1449 if (key
.HasValue(wxT("InternetEncoding")) &&
1450 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1453 // no encoding, see if it's an alias
1454 if (!key
.HasValue(wxT("AliasForCharset")) ||
1455 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1462 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1465 Creates a hidden window with supplied window proc registering the class for
1466 it if necesssary (i.e. the first time only). Caller is responsible for
1467 destroying the window and unregistering the class (note that this must be
1468 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
1469 multiple times into/from the same process so we cna't rely on automatic
1470 Windows class unregistration).
1472 pclassname is a pointer to a caller stored classname, which must initially be
1473 NULL. classname is the desired wndclass classname. If function succesfully
1474 registers the class, pclassname will be set to classname.
1476 extern "C" WXDLLIMPEXP_BASE HWND
1477 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1479 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1480 _T("NULL parameter in wxCreateHiddenWindow") );
1482 // register the class fi we need to first
1483 if ( *pclassname
== NULL
)
1486 wxZeroMemory(wndclass
);
1488 wndclass
.lpfnWndProc
= wndproc
;
1489 wndclass
.hInstance
= wxGetInstance();
1490 wndclass
.lpszClassName
= classname
;
1492 if ( !::RegisterClass(&wndclass
) )
1494 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1499 *pclassname
= classname
;
1502 // next create the window
1503 HWND hwnd
= ::CreateWindow
1517 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));