1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utils.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
34 #include "wx/msw/registry.h"
35 #include "wx/apptrait.h"
36 #include "wx/dynlib.h"
37 #include "wx/dynload.h"
38 #include "wx/scopeguard.h"
39 #include "wx/filename.h"
41 #include "wx/confbase.h" // for wxExpandEnvVars()
43 #include "wx/msw/private.h" // includes <windows.h>
44 #include "wx/msw/private/hiddenwin.h"
45 #include "wx/msw/missing.h" // for CHARSET_HANGUL
47 #if defined(__CYGWIN__)
48 //CYGWIN gives annoying warning about runtime stuff if we don't do this
49 # define USE_SYS_TYPES_FD_SET
50 # include <sys/types.h>
53 // Doesn't work with Cygwin at present
54 #if wxUSE_SOCKETS && (defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) || defined(__CYGWIN32__))
55 // apparently we need to include winsock.h to get WSADATA and other stuff
56 // used in wxGetFullHostName() with the old mingw32 versions
60 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
68 #if defined(__CYGWIN__)
69 #include <sys/unistd.h>
71 #include <sys/cygwin.h> // for cygwin_conv_path()
72 // and cygwin_conv_to_full_win32_path()
73 #include <cygwin/version.h>
76 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
77 // this (3.1 I believe) and how to test for it.
78 // If this works for Borland 4.0 as well, then no worries.
82 // VZ: there is some code using NetXXX() functions to get the full user name:
83 // I don't think it's a good idea because they don't work under Win95 and
84 // seem to return the same as wxGetUserId() under NT. If you really want
85 // to use them, just #define USE_NET_API
92 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
103 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
108 // For wxKillAllChildren
109 #include <tlhelp32.h>
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 // In the WIN.INI file
116 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__)
117 static const wxChar WX_SECTION
[] = wxT("wxWindows");
120 #if (!defined(USE_NET_API) && !defined(__WXWINCE__))
121 static const wxChar eUSERNAME
[] = wxT("UserName");
124 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxUserResourceStr
= wxT("TEXT");
126 // ============================================================================
128 // ============================================================================
130 // ----------------------------------------------------------------------------
131 // get host name and related
132 // ----------------------------------------------------------------------------
134 // Get hostname only (without domain name)
135 bool wxGetHostName(wxChar
*buf
, int maxSize
)
137 #if defined(__WXWINCE__)
138 // GetComputerName() is not supported but the name seems to be stored in
139 // this location in the registry, at least for PPC2003 and WM5
141 wxRegKey
regKey(wxRegKey::HKLM
, wxT("Ident"));
142 if ( !regKey
.HasValue(wxT("Name")) ||
143 !regKey
.QueryValue(wxT("Name"), hostName
) )
146 wxStrlcpy(buf
, hostName
.wx_str(), maxSize
);
147 #else // !__WXWINCE__
148 DWORD nSize
= maxSize
;
149 if ( !::GetComputerName(buf
, &nSize
) )
151 wxLogLastError(wxT("GetComputerName"));
155 #endif // __WXWINCE__/!__WXWINCE__
160 // get full hostname (with domain name if possible)
161 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
163 #if !defined( __WXMICROWIN__) && wxUSE_DYNLIB_CLASS && 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(wxT("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(wxT(#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 wxStrlcpy(buf
, host
.c_str(), 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__)
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
);
268 // Get user name e.g. Julian Smart
269 bool wxGetUserName(wxChar
*buf
, int maxSize
)
271 wxCHECK_MSG( buf
&& ( maxSize
> 0 ), false,
272 wxT("empty buffer in wxGetUserName") );
273 #if defined(__WXWINCE__) && wxUSE_REGKEY
275 wxRegKey
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner"));
276 if(!key
.Open(wxRegKey::Read
))
279 if(!key
.QueryValue(wxT("Owner"),name
))
281 wxStrlcpy(buf
, name
.c_str(), 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("Cannot 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 wxStrlcpy(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__) && !defined(__WINE__)
373 const wxChar
*szHome
= wxGetenv(wxT("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 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
390 cygwin_conv_path(CCP_POSIX_TO_WIN_W
, strDir
, windowsPath
, MAX_PATH
);
392 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
394 strDir
= windowsPath
;
396 #elif defined(__WXWINCE__)
401 // If we have a valid HOME directory, as is used on many machines that
402 // have unix utilities on them, we should use that.
403 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
405 if ( szHome
!= NULL
)
409 else // no HOME, try HOMEDRIVE/PATH
411 szHome
= wxGetenv(wxT("HOMEDRIVE"));
412 if ( szHome
!= NULL
)
414 szHome
= wxGetenv(wxT("HOMEPATH"));
416 if ( szHome
!= NULL
)
420 // the idea is that under NT these variables have default values
421 // of "%systemdrive%:" and "\\". As we don't want to create our
422 // config files in the root directory of the system drive, we will
423 // create it in our program's dir. However, if the user took care
424 // to set HOMEPATH to something other than "\\", we suppose that he
425 // knows what he is doing and use the supplied value.
426 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
431 if ( strDir
.empty() )
433 // If we have a valid USERPROFILE directory, as is the case in
434 // Windows NT, 2000 and XP, we should use that as our home directory.
435 szHome
= wxGetenv(wxT("USERPROFILE"));
437 if ( szHome
!= NULL
)
441 if ( !strDir
.empty() )
443 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
444 // value once again, it shouldn't hurt anyhow
445 strDir
= wxExpandEnvVars(strDir
);
447 else // fall back to the program directory
449 // extract the directory component of the program file name
450 wxFileName::SplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
454 return strDir
.c_str();
457 wxString
wxGetUserHome(const wxString
& user
)
461 if ( user
.empty() || user
== wxGetUserId() )
467 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
),
468 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pTotal
),
469 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pFree
))
478 // old w32api don't have ULARGE_INTEGER
479 #if defined(__WIN32__) && \
480 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
481 // GetDiskFreeSpaceEx() is not available under original Win95, check for
483 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
489 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
491 ::GetModuleHandle(wxT("kernel32.dll")),
493 "GetDiskFreeSpaceExW"
495 "GetDiskFreeSpaceExA"
499 if ( pGetDiskFreeSpaceEx
)
501 ULARGE_INTEGER bytesFree
, bytesTotal
;
503 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
504 if ( !pGetDiskFreeSpaceEx(path
.t_str(),
509 wxLogLastError(wxT("GetDiskFreeSpaceEx"));
514 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
515 // two 32 bit fields which may be or may be not named - try to make it
516 // compile in all cases
517 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
525 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
527 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
);
534 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
536 *pFree
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
);
543 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
544 // should be used instead - but if it's not available, fall back on
545 // GetDiskFreeSpace() nevertheless...
547 DWORD lSectorsPerCluster
,
549 lNumberOfFreeClusters
,
550 lTotalNumberOfClusters
;
552 // FIXME: this is wrong, we should extract the root drive from path
553 // instead, but this is the job for wxFileName...
554 if ( !::GetDiskFreeSpace(path
.t_str(),
557 &lNumberOfFreeClusters
,
558 &lTotalNumberOfClusters
) )
560 wxLogLastError(wxT("GetDiskFreeSpace"));
565 wxDiskspaceSize_t lBytesPerCluster
= (wxDiskspaceSize_t
) lSectorsPerCluster
;
566 lBytesPerCluster
*= lBytesPerSector
;
570 *pTotal
= lBytesPerCluster
;
571 *pTotal
*= lTotalNumberOfClusters
;
576 *pFree
= lBytesPerCluster
;
577 *pFree
*= lNumberOfFreeClusters
;
586 // ----------------------------------------------------------------------------
588 // ----------------------------------------------------------------------------
590 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
591 wxString
*WXUNUSED_IN_WINCE(value
))
594 // no environment variables under CE
597 // first get the size of the buffer
598 DWORD dwRet
= ::GetEnvironmentVariable(var
.t_str(), NULL
, 0);
601 // this means that there is no such variable
607 (void)::GetEnvironmentVariable(var
.t_str(),
608 wxStringBuffer(*value
, dwRet
),
616 bool wxDoSetEnv(const wxString
& var
, const wxChar
*value
)
619 // no environment variables under CE
623 #else // !__WXWINCE__
624 // update the CRT environment if possible as people expect getenv() to also
625 // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
626 // the CRT does use Win32 call to update the process environment block so
627 // there is no need to call it)
629 // TODO: add checks for the other compilers (and update wxSetEnv()
630 // documentation in interface/wx/utils.h accordingly)
631 #if defined(__VISUALC__) || defined(__MINGW32__)
632 // notice that Microsoft _putenv() has different semantics from POSIX
633 // function with almost the same name: in particular it makes a copy of the
634 // string instead of using it as part of environment so we can safely call
635 // it here without going through all the troubles with wxSetEnvModule as in
636 // src/unix/utilsunx.cpp
637 wxString envstr
= var
;
641 _tputenv(envstr
.t_str());
642 #else // other compiler
643 if ( !::SetEnvironmentVariable(var
.t_str(), value
) )
645 wxLogLastError(wxT("SetEnvironmentVariable"));
652 #endif // __WXWINCE__/!__WXWINCE__
655 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
657 return wxDoSetEnv(variable
, value
.t_str());
660 bool wxUnsetEnv(const wxString
& variable
)
662 return wxDoSetEnv(variable
, NULL
);
665 // ----------------------------------------------------------------------------
666 // process management
667 // ----------------------------------------------------------------------------
669 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
670 struct wxFindByPidParams
672 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
674 // the HWND used to return the result
677 // the PID we're looking from
680 wxDECLARE_NO_COPY_CLASS(wxFindByPidParams
);
683 // wxKill helper: EnumWindows() callback which is used to find the first (top
684 // level) window belonging to the given process
685 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
688 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
690 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
691 if ( pid
== params
->pid
)
693 // remember the window we found
696 // return FALSE to stop the enumeration
700 // continue enumeration
704 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
);
706 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
, int flags
)
708 if (flags
& wxKILL_CHILDREN
)
709 wxKillAllChildren(pid
, sig
, krc
);
711 // get the process handle to operate on
712 DWORD dwAccess
= PROCESS_QUERY_INFORMATION
| SYNCHRONIZE
;
713 if ( sig
== wxSIGKILL
)
714 dwAccess
|= PROCESS_TERMINATE
;
716 HANDLE hProcess
= ::OpenProcess(dwAccess
, FALSE
, (DWORD
)pid
);
717 if ( hProcess
== NULL
)
721 // recognize wxKILL_ACCESS_DENIED as special because this doesn't
722 // mean that the process doesn't exist and this is important for
723 // wxProcess::Exists()
724 *krc
= ::GetLastError() == ERROR_ACCESS_DENIED
725 ? wxKILL_ACCESS_DENIED
732 wxON_BLOCK_EXIT1(::CloseHandle
, hProcess
);
734 // Default timeout for waiting for the process termination after killing
735 // it. It should be long enough to allow the process to terminate even on a
736 // busy system but short enough to avoid blocking the main thread for too
738 DWORD waitTimeout
= 500; // ms
744 // kill the process forcefully returning -1 as error code
745 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
747 wxLogSysError(_("Failed to kill process %d"), pid
);
751 // this is not supposed to happen if we could open the
761 // Opening the process handle may succeed for a process even if it
762 // doesn't run any more (typically because open handles to it still
763 // exist elsewhere, possibly in this process itself if we're
764 // killing a child process) so we still need check if it hasn't
765 // terminated yet but, unlike when killing it, we don't need to
766 // wait for any time at all.
771 // any other signal means "terminate"
773 wxFindByPidParams params
;
774 params
.pid
= (DWORD
)pid
;
776 // EnumWindows() has nice semantics: it returns 0 if it found
777 // something or if an error occurred and non zero if it
778 // enumerated all the window
779 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
781 // did we find any window?
784 // tell the app to close
786 // NB: this is the harshest way, the app won't have an
787 // opportunity to save any files, for example, but
788 // this is probably what we want here. If not we
789 // can also use SendMesageTimeout(WM_CLOSE)
790 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
792 wxLogLastError(wxT("PostMessage(WM_QUIT)"));
795 else // it was an error then
797 wxLogLastError(wxT("EnumWindows"));
802 else // no windows for this PID
815 // as we wait for a short time, we can use just WaitForSingleObject()
816 // and not MsgWaitForMultipleObjects()
817 switch ( ::WaitForSingleObject(hProcess
, waitTimeout
) )
820 // Process terminated: normally this indicates that we
821 // successfully killed it but when testing for the process
822 // existence, this means failure.
823 if ( sig
== wxSIGNONE
)
826 *krc
= wxKILL_NO_PROCESS
;
833 wxFAIL_MSG( wxT("unexpected WaitForSingleObject() return") );
837 wxLogLastError(wxT("WaitForSingleObject"));
841 // Process didn't terminate: normally this is a failure but not
842 // when we're just testing for its existence.
843 if ( sig
!= wxSIGNONE
)
855 // the return code is the same as from Unix kill(): 0 if killed
856 // successfully or -1 on error
866 typedef HANDLE (WINAPI
*CreateToolhelp32Snapshot_t
)(DWORD
,DWORD
);
867 typedef BOOL (WINAPI
*Process32_t
)(HANDLE
,LPPROCESSENTRY32
);
869 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot
;
870 Process32_t lpfProcess32First
, lpfProcess32Next
;
872 static void InitToolHelp32()
874 static bool s_initToolHelpDone
= false;
876 if (s_initToolHelpDone
)
879 s_initToolHelpDone
= true;
881 lpfCreateToolhelp32Snapshot
= NULL
;
882 lpfProcess32First
= NULL
;
883 lpfProcess32Next
= NULL
;
885 #if wxUSE_DYNLIB_CLASS
887 wxDynamicLibrary
dllKernel(wxT("kernel32.dll"), wxDL_VERBATIM
);
889 // Get procedure addresses.
890 // We are linking to these functions of Kernel32
891 // explicitly, because otherwise a module using
892 // this code would fail to load under Windows NT,
893 // which does not have the Toolhelp32
894 // functions in the Kernel 32.
895 lpfCreateToolhelp32Snapshot
=
896 (CreateToolhelp32Snapshot_t
)dllKernel
.RawGetSymbol(wxT("CreateToolhelp32Snapshot"));
899 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32First"));
902 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32Next"));
904 #endif // wxUSE_DYNLIB_CLASS
908 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
)
915 // If not implemented for this platform (e.g. NT 4.0), silently ignore
916 if (!lpfCreateToolhelp32Snapshot
|| !lpfProcess32First
|| !lpfProcess32Next
)
919 // Take a snapshot of all processes in the system.
920 HANDLE hProcessSnap
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
921 if (hProcessSnap
== INVALID_HANDLE_VALUE
) {
927 //Fill in the size of the structure before using it.
930 pe
.dwSize
= sizeof(PROCESSENTRY32
);
932 // Walk the snapshot of the processes, and for each process,
933 // kill it if its parent is pid.
934 if (!lpfProcess32First(hProcessSnap
, &pe
)) {
935 // Can't get first process.
938 CloseHandle (hProcessSnap
);
943 if (pe
.th32ParentProcessID
== (DWORD
) pid
) {
944 if (wxKill(pe
.th32ProcessID
, sig
, krc
))
947 } while (lpfProcess32Next (hProcessSnap
, &pe
));
953 // Execute a program in an Interactive Shell
954 bool wxShell(const wxString
& command
)
961 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
963 shell
= (wxChar
*) wxT("\\COMMAND.COM");
972 // pass the command to execute to the command processor
973 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
977 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
980 // Shutdown or reboot the PC
981 bool wxShutdown(int WXUNUSED_IN_WINCE(flags
))
986 #elif defined(__WIN32__)
989 if ( wxGetOsVersion(NULL
, NULL
) == wxOS_WINDOWS_NT
) // if is NT or 2K
991 // Get a token for this process.
993 bOK
= ::OpenProcessToken(GetCurrentProcess(),
994 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
998 TOKEN_PRIVILEGES tkp
;
1000 // Get the LUID for the shutdown privilege.
1001 bOK
= ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
1002 &tkp
.Privileges
[0].Luid
) != 0;
1006 tkp
.PrivilegeCount
= 1; // one privilege to set
1007 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1009 // Get the shutdown privilege for this process.
1010 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
1011 (PTOKEN_PRIVILEGES
)NULL
, 0);
1013 // Cannot test the return value of AdjustTokenPrivileges.
1014 bOK
= ::GetLastError() == ERROR_SUCCESS
;
1017 ::CloseHandle(hToken
);
1024 if ( flags
& wxSHUTDOWN_FORCE
)
1027 flags
&= ~wxSHUTDOWN_FORCE
;
1032 case wxSHUTDOWN_POWEROFF
:
1033 wFlags
|= EWX_POWEROFF
;
1036 case wxSHUTDOWN_REBOOT
:
1037 wFlags
|= EWX_REBOOT
;
1040 case wxSHUTDOWN_LOGOFF
:
1041 wFlags
|= EWX_LOGOFF
;
1045 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
1049 bOK
= ::ExitWindowsEx(wFlags
, 0) != 0;
1053 #endif // WinCE/!WinCE
1056 // ----------------------------------------------------------------------------
1058 // ----------------------------------------------------------------------------
1060 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1061 wxMemorySize
wxGetFreeMemory()
1063 #if defined(__WIN64__)
1064 MEMORYSTATUSEX memStatex
;
1065 memStatex
.dwLength
= sizeof (memStatex
);
1066 ::GlobalMemoryStatusEx (&memStatex
);
1067 return (wxMemorySize
)memStatex
.ullAvailPhys
;
1068 #else /* if defined(__WIN32__) */
1069 MEMORYSTATUS memStatus
;
1070 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1071 ::GlobalMemoryStatus(&memStatus
);
1072 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1076 unsigned long wxGetProcessId()
1078 return ::GetCurrentProcessId();
1084 ::MessageBeep((UINT
)-1); // default sound
1087 bool wxIsDebuggerRunning()
1089 #if wxUSE_DYNLIB_CLASS
1090 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1091 wxDynamicLibrary
dll(wxT("kernel32.dll"), wxDL_VERBATIM
);
1093 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1094 if ( !dll
.HasSymbol(wxT("IsDebuggerPresent")) )
1096 // no way to know, assume no
1100 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(wxT("IsDebuggerPresent")))() != 0;
1106 // ----------------------------------------------------------------------------
1107 // working with MSW resources
1108 // ----------------------------------------------------------------------------
1111 wxLoadUserResource(const void **outData
,
1113 const wxString
& resourceName
,
1114 const wxString
& resourceType
,
1115 WXHINSTANCE instance
)
1117 wxCHECK_MSG( outData
&& outLen
, false, "output pointers can't be NULL" );
1119 HRSRC hResource
= ::FindResource(instance
,
1120 resourceName
.wx_str(),
1121 resourceType
.wx_str());
1125 HGLOBAL hData
= ::LoadResource(instance
, hResource
);
1128 wxLogSysError(_("Failed to load resource \"%s\"."), resourceName
);
1132 *outData
= ::LockResource(hData
);
1135 wxLogSysError(_("Failed to lock resource \"%s\"."), resourceName
);
1139 *outLen
= ::SizeofResource(instance
, hResource
);
1141 // Notice that we do not need to call neither UnlockResource() (which is
1142 // obsolete in Win32) nor GlobalFree() (resources are freed on process
1143 // termination only)
1149 wxLoadUserResource(const wxString
& resourceName
,
1150 const wxString
& resourceType
,
1152 WXHINSTANCE instance
)
1156 if ( !wxLoadUserResource(&data
, &len
, resourceName
, resourceType
, instance
) )
1159 char *s
= new char[len
+ 1];
1160 memcpy(s
, data
, len
);
1161 s
[len
] = '\0'; // NUL-terminate in case the resource itself wasn't
1169 // ----------------------------------------------------------------------------
1171 // ----------------------------------------------------------------------------
1173 // check if we're running under a server or workstation Windows system: it
1174 // returns true or false with obvious meaning as well as -1 if the system type
1175 // couldn't be determined
1177 // this function is currently private but we may want to expose it later if
1178 // it's really useful
1182 int wxIsWindowsServer()
1184 #ifdef VER_NT_WORKSTATION
1185 OSVERSIONINFOEX info
;
1188 info
.dwOSVersionInfoSize
= sizeof(info
);
1189 if ( ::GetVersionEx(reinterpret_cast<OSVERSIONINFO
*>(&info
)) )
1191 switch ( info
.wProductType
)
1193 case VER_NT_WORKSTATION
:
1197 case VER_NT_DOMAIN_CONTROLLER
:
1201 #endif // VER_NT_WORKSTATION
1206 } // anonymous namespace
1208 wxString
wxGetOsDescription()
1215 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1216 if ( ::GetVersionEx(&info
) )
1218 switch ( info
.dwPlatformId
)
1220 #ifdef VER_PLATFORM_WIN32_CE
1221 case VER_PLATFORM_WIN32_CE
:
1222 str
.Printf(_("Windows CE (%d.%d)"),
1223 info
.dwMajorVersion
,
1224 info
.dwMinorVersion
);
1227 case VER_PLATFORM_WIN32s
:
1228 str
= _("Win32s on Windows 3.1");
1231 case VER_PLATFORM_WIN32_WINDOWS
:
1232 switch (info
.dwMinorVersion
)
1235 if ( info
.szCSDVersion
[1] == 'B' ||
1236 info
.szCSDVersion
[1] == 'C' )
1238 str
= _("Windows 95 OSR2");
1242 str
= _("Windows 95");
1246 if ( info
.szCSDVersion
[1] == 'B' ||
1247 info
.szCSDVersion
[1] == 'C' )
1249 str
= _("Windows 98 SE");
1253 str
= _("Windows 98");
1257 str
= _("Windows ME");
1260 str
.Printf(_("Windows 9x (%d.%d)"),
1261 info
.dwMajorVersion
,
1262 info
.dwMinorVersion
);
1265 if ( !wxIsEmpty(info
.szCSDVersion
) )
1267 str
<< wxT(" (") << info
.szCSDVersion
<< wxT(')');
1271 case VER_PLATFORM_WIN32_NT
:
1272 switch ( info
.dwMajorVersion
)
1275 switch ( info
.dwMinorVersion
)
1278 str
= _("Windows 2000");
1282 // we can't distinguish between XP 64 and 2003
1283 // as they both are 5.2, so examine the product
1284 // type to resolve this ambiguity
1285 if ( wxIsWindowsServer() == 1 )
1287 str
= _("Windows Server 2003");
1290 //else: must be XP, fall through
1293 str
= _("Windows XP");
1299 switch ( info
.dwMinorVersion
)
1302 str
= wxIsWindowsServer() == 1
1303 ? _("Windows Server 2008")
1304 : _("Windows Vista");
1308 str
= wxIsWindowsServer() == 1
1309 ? _("Windows Server 2008 R2")
1318 str
.Printf(_("Windows NT %lu.%lu"),
1319 info
.dwMajorVersion
,
1320 info
.dwMinorVersion
);
1324 << wxString::Format(_("build %lu"), info
.dwBuildNumber
);
1325 if ( !wxIsEmpty(info
.szCSDVersion
) )
1327 str
<< wxT(", ") << info
.szCSDVersion
;
1331 if ( wxIsPlatform64Bit() )
1332 str
<< _(", 64-bit edition");
1338 wxFAIL_MSG( wxT("GetVersionEx() failed") ); // should never happen
1344 bool wxIsPlatform64Bit()
1347 return true; // 64-bit programs run only on Win64
1348 #elif wxUSE_DYNLIB_CLASS // Win32
1349 // 32-bit programs run on both 32-bit and 64-bit Windows so check
1350 typedef BOOL (WINAPI
*IsWow64Process_t
)(HANDLE
, BOOL
*);
1352 wxDynamicLibrary
dllKernel32(wxT("kernel32.dll"));
1353 IsWow64Process_t pfnIsWow64Process
=
1354 (IsWow64Process_t
)dllKernel32
.RawGetSymbol(wxT("IsWow64Process"));
1357 if ( pfnIsWow64Process
)
1359 pfnIsWow64Process(::GetCurrentProcess(), &wow64
);
1361 //else: running under a system without Win64 support
1363 return wow64
!= FALSE
;
1366 #endif // Win64/Win32
1369 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1373 // this may be false, true or -1 if we tried to initialize but failed
1376 wxOperatingSystemId os
;
1382 // query the OS info only once as it's not supposed to change
1383 if ( !s_version
.initialized
)
1387 info
.dwOSVersionInfoSize
= sizeof(info
);
1388 if ( ::GetVersionEx(&info
) )
1390 s_version
.initialized
= true;
1392 #if defined(__WXWINCE__)
1393 s_version
.os
= wxOS_WINDOWS_CE
;
1394 #elif defined(__WXMICROWIN__)
1395 s_version
.os
= wxOS_WINDOWS_MICRO
;
1396 #else // "normal" desktop Windows system, use run-time detection
1397 switch ( info
.dwPlatformId
)
1399 case VER_PLATFORM_WIN32_NT
:
1400 s_version
.os
= wxOS_WINDOWS_NT
;
1403 case VER_PLATFORM_WIN32_WINDOWS
:
1404 s_version
.os
= wxOS_WINDOWS_9X
;
1407 #endif // Windows versions
1409 s_version
.verMaj
= info
.dwMajorVersion
;
1410 s_version
.verMin
= info
.dwMinorVersion
;
1412 else // GetVersionEx() failed
1414 s_version
.initialized
= -1;
1418 if ( s_version
.initialized
== 1 )
1421 *verMaj
= s_version
.verMaj
;
1423 *verMin
= s_version
.verMin
;
1426 // this works even if we were not initialized successfully as the initial
1427 // values of this field is 0 which is wxOS_UNKNOWN and exactly what we need
1428 return s_version
.os
;
1431 wxWinVersion
wxGetWinVersion()
1435 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
1437 case wxOS_WINDOWS_9X
:
1443 return wxWinVersion_95
;
1446 return wxWinVersion_98
;
1449 return wxWinVersion_ME
;
1454 case wxOS_WINDOWS_NT
:
1458 return wxWinVersion_NT3
;
1461 return wxWinVersion_NT4
;
1467 return wxWinVersion_2000
;
1470 return wxWinVersion_XP
;
1473 return wxWinVersion_2003
;
1478 return wxWinVersion_NT6
;
1483 // Do nothing just to silence GCC warning
1487 return wxWinVersion_Unknown
;
1490 // ----------------------------------------------------------------------------
1492 // ----------------------------------------------------------------------------
1494 void wxMilliSleep(unsigned long milliseconds
)
1496 ::Sleep(milliseconds
);
1499 void wxMicroSleep(unsigned long microseconds
)
1501 wxMilliSleep(microseconds
/1000);
1504 void wxSleep(int nSecs
)
1506 wxMilliSleep(1000*nSecs
);
1509 // ----------------------------------------------------------------------------
1510 // font encoding <-> Win32 codepage conversion functions
1511 // ----------------------------------------------------------------------------
1513 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1517 // although this function is supposed to return an exact match, do do
1518 // some mappings here for the most common case of "standard" encoding
1519 case wxFONTENCODING_SYSTEM
:
1520 return DEFAULT_CHARSET
;
1522 case wxFONTENCODING_ISO8859_1
:
1523 case wxFONTENCODING_ISO8859_15
:
1524 case wxFONTENCODING_CP1252
:
1525 return ANSI_CHARSET
;
1527 #if !defined(__WXMICROWIN__)
1528 // The following four fonts are multi-byte charsets
1529 case wxFONTENCODING_CP932
:
1530 return SHIFTJIS_CHARSET
;
1532 case wxFONTENCODING_CP936
:
1533 return GB2312_CHARSET
;
1536 case wxFONTENCODING_CP949
:
1537 return HANGUL_CHARSET
;
1540 case wxFONTENCODING_CP950
:
1541 return CHINESEBIG5_CHARSET
;
1543 // The rest are single byte encodings
1544 case wxFONTENCODING_CP1250
:
1545 return EASTEUROPE_CHARSET
;
1547 case wxFONTENCODING_CP1251
:
1548 return RUSSIAN_CHARSET
;
1550 case wxFONTENCODING_CP1253
:
1551 return GREEK_CHARSET
;
1553 case wxFONTENCODING_CP1254
:
1554 return TURKISH_CHARSET
;
1556 case wxFONTENCODING_CP1255
:
1557 return HEBREW_CHARSET
;
1559 case wxFONTENCODING_CP1256
:
1560 return ARABIC_CHARSET
;
1562 case wxFONTENCODING_CP1257
:
1563 return BALTIC_CHARSET
;
1565 case wxFONTENCODING_CP874
:
1566 return THAI_CHARSET
;
1567 #endif // !__WXMICROWIN__
1569 case wxFONTENCODING_CP437
:
1573 // no way to translate this encoding into a Windows charset
1578 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1579 // looks up the vlaues in the registry and the new one which is more
1580 // politically correct and has more chances to work on other Windows versions
1581 // as well but the old version is still needed for !wxUSE_FONTMAP case
1584 #include "wx/fontmap.h"
1586 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1588 // There don't seem to be symbolic names for
1589 // these under Windows so I just copied the
1590 // values from MSDN.
1596 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1597 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1598 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1599 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1600 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1601 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1602 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1603 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1604 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1605 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1606 case wxFONTENCODING_ISO8859_11
: ret
= 874; break;
1607 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1608 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1609 // case wxFONTENCODING_ISO8859_14: ret = 28604; break; // no correspondence on Windows
1610 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1612 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1613 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1615 case wxFONTENCODING_CP437
: ret
= 437; break;
1616 case wxFONTENCODING_CP850
: ret
= 850; break;
1617 case wxFONTENCODING_CP852
: ret
= 852; break;
1618 case wxFONTENCODING_CP855
: ret
= 855; break;
1619 case wxFONTENCODING_CP866
: ret
= 866; break;
1620 case wxFONTENCODING_CP874
: ret
= 874; break;
1621 case wxFONTENCODING_CP932
: ret
= 932; break;
1622 case wxFONTENCODING_CP936
: ret
= 936; break;
1623 case wxFONTENCODING_CP949
: ret
= 949; break;
1624 case wxFONTENCODING_CP950
: ret
= 950; break;
1625 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1626 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1627 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1628 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1629 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1630 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1631 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1632 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1634 case wxFONTENCODING_EUC_JP
: ret
= 20932; break;
1636 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1637 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1638 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1639 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1640 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1641 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1642 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1643 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1644 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1645 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1646 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1647 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1648 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1649 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1651 case wxFONTENCODING_ISO2022_JP
: ret
= 50222; break;
1653 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1654 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1659 if (::IsValidCodePage(ret
) == 0)
1663 if (::GetCPInfo(ret
, &info
) == 0)
1669 extern long wxCharsetToCodepage(const char *name
)
1671 // first get the font encoding for this charset
1675 wxFontEncoding enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
1676 if ( enc
== wxFONTENCODING_SYSTEM
)
1679 // the use the helper function
1680 return wxEncodingToCodepage(enc
);
1683 #else // !wxUSE_FONTMAP
1685 #include "wx/msw/registry.h"
1687 // this should work if Internet Exploiter is installed
1688 extern long wxCharsetToCodepage(const char *name
)
1696 wxString
path(wxT("MIME\\Database\\Charset\\"));
1699 // follow the alias loop
1702 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1707 // two cases: either there's an AliasForCharset string,
1708 // or there are Codepage and InternetEncoding dwords.
1709 // The InternetEncoding gives us the actual encoding,
1710 // the Codepage just says which Windows character set to
1711 // use when displaying the data.
1712 if (key
.HasValue(wxT("InternetEncoding")) &&
1713 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1716 // no encoding, see if it's an alias
1717 if (!key
.HasValue(wxT("AliasForCharset")) ||
1718 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1721 #endif // wxUSE_REGKEY
1726 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1728 extern "C" WXDLLIMPEXP_BASE HWND
1729 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1731 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1732 wxT("NULL parameter in wxCreateHiddenWindow") );
1734 // register the class fi we need to first
1735 if ( *pclassname
== NULL
)
1738 wxZeroMemory(wndclass
);
1740 wndclass
.lpfnWndProc
= wndproc
;
1741 wndclass
.hInstance
= wxGetInstance();
1742 wndclass
.lpszClassName
= classname
;
1744 if ( !::RegisterClass(&wndclass
) )
1746 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1751 *pclassname
= classname
;
1754 // next create the window
1755 HWND hwnd
= ::CreateWindow
1769 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));