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__)
66 #if defined(__CYGWIN__)
67 #include <sys/unistd.h>
69 #include <sys/cygwin.h> // for cygwin_conv_path()
70 // and cygwin_conv_to_full_win32_path()
71 #include <cygwin/version.h>
74 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
75 // this (3.1 I believe) and how to test for it.
76 // If this works for Borland 4.0 as well, then no worries.
80 // VZ: there is some code using NetXXX() functions to get the full user name:
81 // I don't think it's a good idea because they don't work under Win95 and
82 // seem to return the same as wxGetUserId() under NT. If you really want
83 // to use them, just #define USE_NET_API
90 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
101 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
106 // For wxKillAllChildren
107 #include <tlhelp32.h>
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // In the WIN.INI file
114 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__)
115 static const wxChar WX_SECTION
[] = wxT("wxWindows");
118 #if (!defined(USE_NET_API) && !defined(__WXWINCE__))
119 static const wxChar eUSERNAME
[] = wxT("UserName");
122 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxUserResourceStr
= wxT("TEXT");
124 // ============================================================================
126 // ============================================================================
128 // ----------------------------------------------------------------------------
129 // get host name and related
130 // ----------------------------------------------------------------------------
132 // Get hostname only (without domain name)
133 bool wxGetHostName(wxChar
*buf
, int maxSize
)
135 #if defined(__WXWINCE__)
136 // GetComputerName() is not supported but the name seems to be stored in
137 // this location in the registry, at least for PPC2003 and WM5
139 wxRegKey
regKey(wxRegKey::HKLM
, wxT("Ident"));
140 if ( !regKey
.HasValue(wxT("Name")) ||
141 !regKey
.QueryValue(wxT("Name"), hostName
) )
144 wxStrlcpy(buf
, hostName
.t_str(), maxSize
);
145 #else // !__WXWINCE__
146 DWORD nSize
= maxSize
;
147 if ( !::GetComputerName(buf
, &nSize
) )
149 wxLogLastError(wxT("GetComputerName"));
153 #endif // __WXWINCE__/!__WXWINCE__
158 // get full hostname (with domain name if possible)
159 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
161 #if !defined( __WXMICROWIN__) && wxUSE_DYNLIB_CLASS && 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(wxT("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(wxT(#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 wxStrlcpy(buf
, host
.c_str(), 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__)
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
);
266 // Get user name e.g. Julian Smart
267 bool wxGetUserName(wxChar
*buf
, int maxSize
)
269 wxCHECK_MSG( buf
&& ( maxSize
> 0 ), false,
270 wxT("empty buffer in wxGetUserName") );
271 #if defined(__WXWINCE__) && wxUSE_REGKEY
273 wxRegKey
key(wxRegKey::HKCU
, wxT("ControlPanel\\Owner"));
274 if(!key
.Open(wxRegKey::Read
))
277 if(!key
.QueryValue(wxT("Owner"),name
))
279 wxStrlcpy(buf
, name
.c_str(), maxSize
);
281 #elif defined(USE_NET_API)
282 CHAR szUserName
[256];
283 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
286 // TODO how to get the domain name?
289 // the code is based on the MSDN example (also see KB article Q119670)
290 WCHAR wszUserName
[256]; // Unicode user name
291 WCHAR wszDomain
[256];
294 USER_INFO_2
*ui2
; // User structure
296 // Convert ANSI user name and domain to Unicode
297 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
298 wszUserName
, WXSIZEOF(wszUserName
) );
299 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
300 wszDomain
, WXSIZEOF(wszDomain
) );
302 // Get the computer name of a DC for the domain.
303 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
305 wxLogError(wxT("Cannot find domain controller"));
310 // Look up the user on the DC
311 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
312 (LPWSTR
)&wszUserName
,
313 2, // level - we want USER_INFO_2
321 case NERR_InvalidComputer
:
322 wxLogError(wxT("Invalid domain controller name."));
326 case NERR_UserNotFound
:
327 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
332 wxLogSysError(wxT("Can't get information about user"));
337 // Convert the Unicode full name to ANSI
338 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
339 buf
, maxSize
, NULL
, NULL
);
344 wxLogError(wxT("Couldn't look up full user name."));
347 #else // !USE_NET_API
348 // Could use NIS, MS-Mail or other site specific programs
349 // Use wxWidgets configuration data
350 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize
- 1) != 0;
353 ok
= wxGetUserId(buf
, maxSize
);
358 wxStrlcpy(buf
, wxT("Unknown User"), maxSize
);
365 const wxChar
* wxGetHomeDir(wxString
*pstr
)
367 wxString
& strDir
= *pstr
;
369 // first branch is for Cygwin
370 #if defined(__UNIX__) && !defined(__WINE__)
371 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
372 if ( szHome
== NULL
) {
374 wxLogWarning(_("can't find user's HOME, using current directory."));
380 // add a trailing slash if needed
381 if ( strDir
.Last() != wxT('/') )
385 // Cygwin returns unix type path but that does not work well
386 static wxChar windowsPath
[MAX_PATH
];
387 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
388 cygwin_conv_path(CCP_POSIX_TO_WIN_W
, strDir
, windowsPath
, MAX_PATH
);
390 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
392 strDir
= windowsPath
;
394 #elif defined(__WXWINCE__)
399 // If we have a valid HOME directory, as is used on many machines that
400 // have unix utilities on them, we should use that.
401 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
403 if ( szHome
!= NULL
)
407 else // no HOME, try HOMEDRIVE/PATH
409 szHome
= wxGetenv(wxT("HOMEDRIVE"));
410 if ( szHome
!= NULL
)
412 szHome
= wxGetenv(wxT("HOMEPATH"));
414 if ( szHome
!= NULL
)
418 // the idea is that under NT these variables have default values
419 // of "%systemdrive%:" and "\\". As we don't want to create our
420 // config files in the root directory of the system drive, we will
421 // create it in our program's dir. However, if the user took care
422 // to set HOMEPATH to something other than "\\", we suppose that he
423 // knows what he is doing and use the supplied value.
424 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
429 if ( strDir
.empty() )
431 // If we have a valid USERPROFILE directory, as is the case in
432 // Windows NT, 2000 and XP, we should use that as our home directory.
433 szHome
= wxGetenv(wxT("USERPROFILE"));
435 if ( szHome
!= NULL
)
439 if ( !strDir
.empty() )
441 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
442 // value once again, it shouldn't hurt anyhow
443 strDir
= wxExpandEnvVars(strDir
);
445 else // fall back to the program directory
447 // extract the directory component of the program file name
448 wxFileName::SplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
);
452 return strDir
.c_str();
455 wxString
wxGetUserHome(const wxString
& user
)
459 if ( user
.empty() || user
== wxGetUserId() )
465 bool wxGetDiskSpace(const wxString
& WXUNUSED_IN_WINCE(path
),
466 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pTotal
),
467 wxDiskspaceSize_t
*WXUNUSED_IN_WINCE(pFree
))
476 // old w32api don't have ULARGE_INTEGER
477 #if defined(__WIN32__) && \
478 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
479 // GetDiskFreeSpaceEx() is not available under original Win95, check for
481 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
487 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
489 ::GetModuleHandle(wxT("kernel32.dll")),
491 "GetDiskFreeSpaceExW"
493 "GetDiskFreeSpaceExA"
497 if ( pGetDiskFreeSpaceEx
)
499 ULARGE_INTEGER bytesFree
, bytesTotal
;
501 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
502 if ( !pGetDiskFreeSpaceEx(path
.t_str(),
507 wxLogLastError(wxT("GetDiskFreeSpaceEx"));
512 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
513 // two 32 bit fields which may be or may be not named - try to make it
514 // compile in all cases
515 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
523 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
525 *pTotal
= wxDiskspaceSize_t(UL(bytesTotal
).LowPart
);
532 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
534 *pFree
= wxDiskspaceSize_t(UL(bytesFree
).LowPart
);
541 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
542 // should be used instead - but if it's not available, fall back on
543 // GetDiskFreeSpace() nevertheless...
545 DWORD lSectorsPerCluster
,
547 lNumberOfFreeClusters
,
548 lTotalNumberOfClusters
;
550 // FIXME: this is wrong, we should extract the root drive from path
551 // instead, but this is the job for wxFileName...
552 if ( !::GetDiskFreeSpace(path
.t_str(),
555 &lNumberOfFreeClusters
,
556 &lTotalNumberOfClusters
) )
558 wxLogLastError(wxT("GetDiskFreeSpace"));
563 wxDiskspaceSize_t lBytesPerCluster
= (wxDiskspaceSize_t
) lSectorsPerCluster
;
564 lBytesPerCluster
*= lBytesPerSector
;
568 *pTotal
= lBytesPerCluster
;
569 *pTotal
*= lTotalNumberOfClusters
;
574 *pFree
= lBytesPerCluster
;
575 *pFree
*= lNumberOfFreeClusters
;
584 // ----------------------------------------------------------------------------
586 // ----------------------------------------------------------------------------
588 bool wxGetEnv(const wxString
& WXUNUSED_IN_WINCE(var
),
589 wxString
*WXUNUSED_IN_WINCE(value
))
592 // no environment variables under CE
595 // first get the size of the buffer
596 DWORD dwRet
= ::GetEnvironmentVariable(var
.t_str(), NULL
, 0);
599 // this means that there is no such variable
605 (void)::GetEnvironmentVariable(var
.t_str(),
606 wxStringBuffer(*value
, dwRet
),
614 bool wxDoSetEnv(const wxString
& var
, const wxChar
*value
)
617 // no environment variables under CE
621 #else // !__WXWINCE__
622 // update the CRT environment if possible as people expect getenv() to also
623 // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
624 // the CRT does use Win32 call to update the process environment block so
625 // there is no need to call it)
627 // TODO: add checks for the other compilers (and update wxSetEnv()
628 // documentation in interface/wx/utils.h accordingly)
629 #if defined(__VISUALC__) || defined(__MINGW32__)
630 // notice that Microsoft _putenv() has different semantics from POSIX
631 // function with almost the same name: in particular it makes a copy of the
632 // string instead of using it as part of environment so we can safely call
633 // it here without going through all the troubles with wxSetEnvModule as in
634 // src/unix/utilsunx.cpp
635 wxString envstr
= var
;
639 if ( _tputenv(envstr
.t_str()) != 0 )
641 #else // other compiler
642 if ( !::SetEnvironmentVariable(var
.t_str(), value
) )
644 wxLogLastError(wxT("SetEnvironmentVariable"));
651 #endif // __WXWINCE__/!__WXWINCE__
654 bool wxSetEnv(const wxString
& variable
, const wxString
& value
)
656 return wxDoSetEnv(variable
, value
.t_str());
659 bool wxUnsetEnv(const wxString
& variable
)
661 return wxDoSetEnv(variable
, NULL
);
664 // ----------------------------------------------------------------------------
665 // process management
666 // ----------------------------------------------------------------------------
668 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
669 struct wxFindByPidParams
671 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
673 // the HWND used to return the result
676 // the PID we're looking from
679 wxDECLARE_NO_COPY_CLASS(wxFindByPidParams
);
682 // wxKill helper: EnumWindows() callback which is used to find the first (top
683 // level) window belonging to the given process
684 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
687 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
689 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
690 if ( pid
== params
->pid
)
692 // remember the window we found
695 // return FALSE to stop the enumeration
699 // continue enumeration
703 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
);
705 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
, int flags
)
707 if (flags
& wxKILL_CHILDREN
)
708 wxKillAllChildren(pid
, sig
, krc
);
710 // get the process handle to operate on
711 DWORD dwAccess
= PROCESS_QUERY_INFORMATION
| SYNCHRONIZE
;
712 if ( sig
== wxSIGKILL
)
713 dwAccess
|= PROCESS_TERMINATE
;
715 HANDLE hProcess
= ::OpenProcess(dwAccess
, FALSE
, (DWORD
)pid
);
716 if ( hProcess
== NULL
)
720 // recognize wxKILL_ACCESS_DENIED as special because this doesn't
721 // mean that the process doesn't exist and this is important for
722 // wxProcess::Exists()
723 *krc
= ::GetLastError() == ERROR_ACCESS_DENIED
724 ? wxKILL_ACCESS_DENIED
731 wxON_BLOCK_EXIT1(::CloseHandle
, hProcess
);
733 // Default timeout for waiting for the process termination after killing
734 // it. It should be long enough to allow the process to terminate even on a
735 // busy system but short enough to avoid blocking the main thread for too
737 DWORD waitTimeout
= 500; // ms
743 // kill the process forcefully returning -1 as error code
744 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
746 wxLogSysError(_("Failed to kill process %d"), pid
);
750 // this is not supposed to happen if we could open the
760 // Opening the process handle may succeed for a process even if it
761 // doesn't run any more (typically because open handles to it still
762 // exist elsewhere, possibly in this process itself if we're
763 // killing a child process) so we still need check if it hasn't
764 // terminated yet but, unlike when killing it, we don't need to
765 // wait for any time at all.
770 // any other signal means "terminate"
772 wxFindByPidParams params
;
773 params
.pid
= (DWORD
)pid
;
775 // EnumWindows() has nice semantics: it returns 0 if it found
776 // something or if an error occurred and non zero if it
777 // enumerated all the window
778 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
780 // did we find any window?
783 // tell the app to close
785 // NB: this is the harshest way, the app won't have an
786 // opportunity to save any files, for example, but
787 // this is probably what we want here. If not we
788 // can also use SendMesageTimeout(WM_CLOSE)
789 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
791 wxLogLastError(wxT("PostMessage(WM_QUIT)"));
794 else // it was an error then
796 wxLogLastError(wxT("EnumWindows"));
801 else // no windows for this PID
814 // as we wait for a short time, we can use just WaitForSingleObject()
815 // and not MsgWaitForMultipleObjects()
816 switch ( ::WaitForSingleObject(hProcess
, waitTimeout
) )
819 // Process terminated: normally this indicates that we
820 // successfully killed it but when testing for the process
821 // existence, this means failure.
822 if ( sig
== wxSIGNONE
)
825 *krc
= wxKILL_NO_PROCESS
;
832 wxFAIL_MSG( wxT("unexpected WaitForSingleObject() return") );
836 wxLogLastError(wxT("WaitForSingleObject"));
840 // Process didn't terminate: normally this is a failure but not
841 // when we're just testing for its existence.
842 if ( sig
!= wxSIGNONE
)
854 // the return code is the same as from Unix kill(): 0 if killed
855 // successfully or -1 on error
865 typedef HANDLE (WINAPI
*CreateToolhelp32Snapshot_t
)(DWORD
,DWORD
);
866 typedef BOOL (WINAPI
*Process32_t
)(HANDLE
,LPPROCESSENTRY32
);
868 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot
;
869 Process32_t lpfProcess32First
, lpfProcess32Next
;
871 static void InitToolHelp32()
873 static bool s_initToolHelpDone
= false;
875 if (s_initToolHelpDone
)
878 s_initToolHelpDone
= true;
880 lpfCreateToolhelp32Snapshot
= NULL
;
881 lpfProcess32First
= NULL
;
882 lpfProcess32Next
= NULL
;
884 #if wxUSE_DYNLIB_CLASS
886 wxDynamicLibrary
dllKernel(wxT("kernel32.dll"), wxDL_VERBATIM
);
888 // Get procedure addresses.
889 // We are linking to these functions of Kernel32
890 // explicitly, because otherwise a module using
891 // this code would fail to load under Windows NT,
892 // which does not have the Toolhelp32
893 // functions in the Kernel 32.
894 lpfCreateToolhelp32Snapshot
=
895 (CreateToolhelp32Snapshot_t
)dllKernel
.RawGetSymbol(wxT("CreateToolhelp32Snapshot"));
898 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32First"));
901 (Process32_t
)dllKernel
.RawGetSymbol(wxT("Process32Next"));
903 #endif // wxUSE_DYNLIB_CLASS
907 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError
*krc
)
914 // If not implemented for this platform (e.g. NT 4.0), silently ignore
915 if (!lpfCreateToolhelp32Snapshot
|| !lpfProcess32First
|| !lpfProcess32Next
)
918 // Take a snapshot of all processes in the system.
919 HANDLE hProcessSnap
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
920 if (hProcessSnap
== INVALID_HANDLE_VALUE
) {
926 //Fill in the size of the structure before using it.
929 pe
.dwSize
= sizeof(PROCESSENTRY32
);
931 // Walk the snapshot of the processes, and for each process,
932 // kill it if its parent is pid.
933 if (!lpfProcess32First(hProcessSnap
, &pe
)) {
934 // Can't get first process.
937 CloseHandle (hProcessSnap
);
942 if (pe
.th32ParentProcessID
== (DWORD
) pid
) {
943 if (wxKill(pe
.th32ProcessID
, sig
, krc
))
946 } while (lpfProcess32Next (hProcessSnap
, &pe
));
952 // Execute a program in an Interactive Shell
953 bool wxShell(const wxString
& command
)
960 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
962 shell
= (wxChar
*) wxT("\\COMMAND.COM");
971 // pass the command to execute to the command processor
972 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
976 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
979 // Shutdown or reboot the PC
980 bool wxShutdown(int WXUNUSED_IN_WINCE(flags
))
985 #elif defined(__WIN32__)
988 if ( wxGetOsVersion(NULL
, NULL
) == wxOS_WINDOWS_NT
) // if is NT or 2K
990 // Get a token for this process.
992 bOK
= ::OpenProcessToken(GetCurrentProcess(),
993 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
997 TOKEN_PRIVILEGES tkp
;
999 // Get the LUID for the shutdown privilege.
1000 bOK
= ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
1001 &tkp
.Privileges
[0].Luid
) != 0;
1005 tkp
.PrivilegeCount
= 1; // one privilege to set
1006 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1008 // Get the shutdown privilege for this process.
1009 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
1010 (PTOKEN_PRIVILEGES
)NULL
, 0);
1012 // Cannot test the return value of AdjustTokenPrivileges.
1013 bOK
= ::GetLastError() == ERROR_SUCCESS
;
1016 ::CloseHandle(hToken
);
1023 if ( flags
& wxSHUTDOWN_FORCE
)
1026 flags
&= ~wxSHUTDOWN_FORCE
;
1031 case wxSHUTDOWN_POWEROFF
:
1032 wFlags
|= EWX_POWEROFF
;
1035 case wxSHUTDOWN_REBOOT
:
1036 wFlags
|= EWX_REBOOT
;
1039 case wxSHUTDOWN_LOGOFF
:
1040 wFlags
|= EWX_LOGOFF
;
1044 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
1048 bOK
= ::ExitWindowsEx(wFlags
, 0) != 0;
1052 #endif // WinCE/!WinCE
1055 // ----------------------------------------------------------------------------
1057 // ----------------------------------------------------------------------------
1059 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1060 wxMemorySize
wxGetFreeMemory()
1062 #if defined(__WIN64__)
1063 MEMORYSTATUSEX memStatex
;
1064 memStatex
.dwLength
= sizeof (memStatex
);
1065 ::GlobalMemoryStatusEx (&memStatex
);
1066 return (wxMemorySize
)memStatex
.ullAvailPhys
;
1067 #else /* if defined(__WIN32__) */
1068 MEMORYSTATUS memStatus
;
1069 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
1070 ::GlobalMemoryStatus(&memStatus
);
1071 return (wxMemorySize
)memStatus
.dwAvailPhys
;
1075 unsigned long wxGetProcessId()
1077 return ::GetCurrentProcessId();
1080 bool wxIsDebuggerRunning()
1082 #if wxUSE_DYNLIB_CLASS
1083 // IsDebuggerPresent() is not available under Win95, so load it dynamically
1084 wxDynamicLibrary
dll(wxT("kernel32.dll"), wxDL_VERBATIM
);
1086 typedef BOOL (WINAPI
*IsDebuggerPresent_t
)();
1087 if ( !dll
.HasSymbol(wxT("IsDebuggerPresent")) )
1089 // no way to know, assume no
1093 return (*(IsDebuggerPresent_t
)dll
.GetSymbol(wxT("IsDebuggerPresent")))() != 0;
1099 // ----------------------------------------------------------------------------
1100 // working with MSW resources
1101 // ----------------------------------------------------------------------------
1104 wxLoadUserResource(const void **outData
,
1106 const wxString
& resourceName
,
1107 const wxChar
* resourceType
,
1108 WXHINSTANCE instance
)
1110 wxCHECK_MSG( outData
&& outLen
, false, "output pointers can't be NULL" );
1112 HRSRC hResource
= ::FindResource(instance
,
1113 resourceName
.t_str(),
1118 HGLOBAL hData
= ::LoadResource(instance
, hResource
);
1121 wxLogSysError(_("Failed to load resource \"%s\"."), resourceName
);
1125 *outData
= ::LockResource(hData
);
1128 wxLogSysError(_("Failed to lock resource \"%s\"."), resourceName
);
1132 *outLen
= ::SizeofResource(instance
, hResource
);
1134 // Notice that we do not need to call neither UnlockResource() (which is
1135 // obsolete in Win32) nor GlobalFree() (resources are freed on process
1136 // termination only)
1142 wxLoadUserResource(const wxString
& resourceName
,
1143 const wxChar
* resourceType
,
1145 WXHINSTANCE instance
)
1149 if ( !wxLoadUserResource(&data
, &len
, resourceName
, resourceType
, instance
) )
1152 char *s
= new char[len
+ 1];
1153 memcpy(s
, data
, len
);
1154 s
[len
] = '\0'; // NUL-terminate in case the resource itself wasn't
1162 // ----------------------------------------------------------------------------
1164 // ----------------------------------------------------------------------------
1166 // check if we're running under a server or workstation Windows system: it
1167 // returns true or false with obvious meaning as well as -1 if the system type
1168 // couldn't be determined
1170 // this function is currently private but we may want to expose it later if
1171 // it's really useful
1175 int wxIsWindowsServer()
1177 #ifdef VER_NT_WORKSTATION
1178 OSVERSIONINFOEX info
;
1181 info
.dwOSVersionInfoSize
= sizeof(info
);
1182 if ( ::GetVersionEx(reinterpret_cast<OSVERSIONINFO
*>(&info
)) )
1184 switch ( info
.wProductType
)
1186 case VER_NT_WORKSTATION
:
1190 case VER_NT_DOMAIN_CONTROLLER
:
1194 #endif // VER_NT_WORKSTATION
1199 } // anonymous namespace
1201 wxString
wxGetOsDescription()
1208 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1209 if ( ::GetVersionEx(&info
) )
1211 switch ( info
.dwPlatformId
)
1213 #ifdef VER_PLATFORM_WIN32_CE
1214 case VER_PLATFORM_WIN32_CE
:
1215 str
.Printf(_("Windows CE (%d.%d)"),
1216 info
.dwMajorVersion
,
1217 info
.dwMinorVersion
);
1220 case VER_PLATFORM_WIN32s
:
1221 str
= _("Win32s on Windows 3.1");
1224 case VER_PLATFORM_WIN32_WINDOWS
:
1225 switch (info
.dwMinorVersion
)
1228 if ( info
.szCSDVersion
[1] == 'B' ||
1229 info
.szCSDVersion
[1] == 'C' )
1231 str
= _("Windows 95 OSR2");
1235 str
= _("Windows 95");
1239 if ( info
.szCSDVersion
[1] == 'B' ||
1240 info
.szCSDVersion
[1] == 'C' )
1242 str
= _("Windows 98 SE");
1246 str
= _("Windows 98");
1250 str
= _("Windows ME");
1253 str
.Printf(_("Windows 9x (%d.%d)"),
1254 info
.dwMajorVersion
,
1255 info
.dwMinorVersion
);
1258 if ( !wxIsEmpty(info
.szCSDVersion
) )
1260 str
<< wxT(" (") << info
.szCSDVersion
<< wxT(')');
1264 case VER_PLATFORM_WIN32_NT
:
1265 switch ( info
.dwMajorVersion
)
1268 switch ( info
.dwMinorVersion
)
1271 str
= _("Windows 2000");
1275 // we can't distinguish between XP 64 and 2003
1276 // as they both are 5.2, so examine the product
1277 // type to resolve this ambiguity
1278 if ( wxIsWindowsServer() == 1 )
1280 str
= _("Windows Server 2003");
1283 //else: must be XP, fall through
1286 str
= _("Windows XP");
1292 switch ( info
.dwMinorVersion
)
1295 str
= wxIsWindowsServer() == 1
1296 ? _("Windows Server 2008")
1297 : _("Windows Vista");
1301 str
= wxIsWindowsServer() == 1
1302 ? _("Windows Server 2008 R2")
1311 str
.Printf(_("Windows NT %lu.%lu"),
1312 info
.dwMajorVersion
,
1313 info
.dwMinorVersion
);
1317 << wxString::Format(_("build %lu"), info
.dwBuildNumber
);
1318 if ( !wxIsEmpty(info
.szCSDVersion
) )
1320 str
<< wxT(", ") << info
.szCSDVersion
;
1324 if ( wxIsPlatform64Bit() )
1325 str
<< _(", 64-bit edition");
1331 wxFAIL_MSG( wxT("GetVersionEx() failed") ); // should never happen
1337 bool wxIsPlatform64Bit()
1340 return true; // 64-bit programs run only on Win64
1341 #elif wxUSE_DYNLIB_CLASS // Win32
1342 // 32-bit programs run on both 32-bit and 64-bit Windows so check
1343 typedef BOOL (WINAPI
*IsWow64Process_t
)(HANDLE
, BOOL
*);
1345 wxDynamicLibrary
dllKernel32(wxT("kernel32.dll"));
1346 IsWow64Process_t pfnIsWow64Process
=
1347 (IsWow64Process_t
)dllKernel32
.RawGetSymbol(wxT("IsWow64Process"));
1350 if ( pfnIsWow64Process
)
1352 pfnIsWow64Process(::GetCurrentProcess(), &wow64
);
1354 //else: running under a system without Win64 support
1356 return wow64
!= FALSE
;
1359 #endif // Win64/Win32
1362 wxOperatingSystemId
wxGetOsVersion(int *verMaj
, int *verMin
)
1366 // this may be false, true or -1 if we tried to initialize but failed
1369 wxOperatingSystemId os
;
1375 // query the OS info only once as it's not supposed to change
1376 if ( !s_version
.initialized
)
1380 info
.dwOSVersionInfoSize
= sizeof(info
);
1381 if ( ::GetVersionEx(&info
) )
1383 s_version
.initialized
= true;
1385 #if defined(__WXWINCE__)
1386 s_version
.os
= wxOS_WINDOWS_CE
;
1387 #elif defined(__WXMICROWIN__)
1388 s_version
.os
= wxOS_WINDOWS_MICRO
;
1389 #else // "normal" desktop Windows system, use run-time detection
1390 switch ( info
.dwPlatformId
)
1392 case VER_PLATFORM_WIN32_NT
:
1393 s_version
.os
= wxOS_WINDOWS_NT
;
1396 case VER_PLATFORM_WIN32_WINDOWS
:
1397 s_version
.os
= wxOS_WINDOWS_9X
;
1400 #endif // Windows versions
1402 s_version
.verMaj
= info
.dwMajorVersion
;
1403 s_version
.verMin
= info
.dwMinorVersion
;
1405 else // GetVersionEx() failed
1407 s_version
.initialized
= -1;
1411 if ( s_version
.initialized
== 1 )
1414 *verMaj
= s_version
.verMaj
;
1416 *verMin
= s_version
.verMin
;
1419 // this works even if we were not initialized successfully as the initial
1420 // values of this field is 0 which is wxOS_UNKNOWN and exactly what we need
1421 return s_version
.os
;
1424 wxWinVersion
wxGetWinVersion()
1428 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
1430 case wxOS_WINDOWS_9X
:
1436 return wxWinVersion_95
;
1439 return wxWinVersion_98
;
1442 return wxWinVersion_ME
;
1447 case wxOS_WINDOWS_NT
:
1451 return wxWinVersion_NT3
;
1454 return wxWinVersion_NT4
;
1460 return wxWinVersion_2000
;
1463 return wxWinVersion_XP
;
1466 return wxWinVersion_2003
;
1471 return wxWinVersion_NT6
;
1476 // Do nothing just to silence GCC warning
1480 return wxWinVersion_Unknown
;
1483 // ----------------------------------------------------------------------------
1485 // ----------------------------------------------------------------------------
1487 void wxMilliSleep(unsigned long milliseconds
)
1489 ::Sleep(milliseconds
);
1492 void wxMicroSleep(unsigned long microseconds
)
1494 wxMilliSleep(microseconds
/1000);
1497 void wxSleep(int nSecs
)
1499 wxMilliSleep(1000*nSecs
);
1502 // ----------------------------------------------------------------------------
1503 // font encoding <-> Win32 codepage conversion functions
1504 // ----------------------------------------------------------------------------
1506 extern WXDLLIMPEXP_BASE
long wxEncodingToCharset(wxFontEncoding encoding
)
1510 // although this function is supposed to return an exact match, do do
1511 // some mappings here for the most common case of "standard" encoding
1512 case wxFONTENCODING_SYSTEM
:
1513 return DEFAULT_CHARSET
;
1515 case wxFONTENCODING_ISO8859_1
:
1516 case wxFONTENCODING_ISO8859_15
:
1517 case wxFONTENCODING_CP1252
:
1518 return ANSI_CHARSET
;
1520 #if !defined(__WXMICROWIN__)
1521 // The following four fonts are multi-byte charsets
1522 case wxFONTENCODING_CP932
:
1523 return SHIFTJIS_CHARSET
;
1525 case wxFONTENCODING_CP936
:
1526 return GB2312_CHARSET
;
1529 case wxFONTENCODING_CP949
:
1530 return HANGUL_CHARSET
;
1533 case wxFONTENCODING_CP950
:
1534 return CHINESEBIG5_CHARSET
;
1536 // The rest are single byte encodings
1537 case wxFONTENCODING_CP1250
:
1538 return EASTEUROPE_CHARSET
;
1540 case wxFONTENCODING_CP1251
:
1541 return RUSSIAN_CHARSET
;
1543 case wxFONTENCODING_CP1253
:
1544 return GREEK_CHARSET
;
1546 case wxFONTENCODING_CP1254
:
1547 return TURKISH_CHARSET
;
1549 case wxFONTENCODING_CP1255
:
1550 return HEBREW_CHARSET
;
1552 case wxFONTENCODING_CP1256
:
1553 return ARABIC_CHARSET
;
1555 case wxFONTENCODING_CP1257
:
1556 return BALTIC_CHARSET
;
1558 case wxFONTENCODING_CP874
:
1559 return THAI_CHARSET
;
1560 #endif // !__WXMICROWIN__
1562 case wxFONTENCODING_CP437
:
1566 // no way to translate this encoding into a Windows charset
1571 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1572 // looks up the vlaues in the registry and the new one which is more
1573 // politically correct and has more chances to work on other Windows versions
1574 // as well but the old version is still needed for !wxUSE_FONTMAP case
1577 #include "wx/fontmap.h"
1579 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
)
1581 // There don't seem to be symbolic names for
1582 // these under Windows so I just copied the
1583 // values from MSDN.
1589 case wxFONTENCODING_ISO8859_1
: ret
= 28591; break;
1590 case wxFONTENCODING_ISO8859_2
: ret
= 28592; break;
1591 case wxFONTENCODING_ISO8859_3
: ret
= 28593; break;
1592 case wxFONTENCODING_ISO8859_4
: ret
= 28594; break;
1593 case wxFONTENCODING_ISO8859_5
: ret
= 28595; break;
1594 case wxFONTENCODING_ISO8859_6
: ret
= 28596; break;
1595 case wxFONTENCODING_ISO8859_7
: ret
= 28597; break;
1596 case wxFONTENCODING_ISO8859_8
: ret
= 28598; break;
1597 case wxFONTENCODING_ISO8859_9
: ret
= 28599; break;
1598 case wxFONTENCODING_ISO8859_10
: ret
= 28600; break;
1599 case wxFONTENCODING_ISO8859_11
: ret
= 874; break;
1600 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
1601 case wxFONTENCODING_ISO8859_13
: ret
= 28603; break;
1602 // case wxFONTENCODING_ISO8859_14: ret = 28604; break; // no correspondence on Windows
1603 case wxFONTENCODING_ISO8859_15
: ret
= 28605; break;
1605 case wxFONTENCODING_KOI8
: ret
= 20866; break;
1606 case wxFONTENCODING_KOI8_U
: ret
= 21866; break;
1608 case wxFONTENCODING_CP437
: ret
= 437; break;
1609 case wxFONTENCODING_CP850
: ret
= 850; break;
1610 case wxFONTENCODING_CP852
: ret
= 852; break;
1611 case wxFONTENCODING_CP855
: ret
= 855; break;
1612 case wxFONTENCODING_CP866
: ret
= 866; break;
1613 case wxFONTENCODING_CP874
: ret
= 874; break;
1614 case wxFONTENCODING_CP932
: ret
= 932; break;
1615 case wxFONTENCODING_CP936
: ret
= 936; break;
1616 case wxFONTENCODING_CP949
: ret
= 949; break;
1617 case wxFONTENCODING_CP950
: ret
= 950; break;
1618 case wxFONTENCODING_CP1250
: ret
= 1250; break;
1619 case wxFONTENCODING_CP1251
: ret
= 1251; break;
1620 case wxFONTENCODING_CP1252
: ret
= 1252; break;
1621 case wxFONTENCODING_CP1253
: ret
= 1253; break;
1622 case wxFONTENCODING_CP1254
: ret
= 1254; break;
1623 case wxFONTENCODING_CP1255
: ret
= 1255; break;
1624 case wxFONTENCODING_CP1256
: ret
= 1256; break;
1625 case wxFONTENCODING_CP1257
: ret
= 1257; break;
1627 case wxFONTENCODING_EUC_JP
: ret
= 20932; break;
1629 case wxFONTENCODING_MACROMAN
: ret
= 10000; break;
1630 case wxFONTENCODING_MACJAPANESE
: ret
= 10001; break;
1631 case wxFONTENCODING_MACCHINESETRAD
: ret
= 10002; break;
1632 case wxFONTENCODING_MACKOREAN
: ret
= 10003; break;
1633 case wxFONTENCODING_MACARABIC
: ret
= 10004; break;
1634 case wxFONTENCODING_MACHEBREW
: ret
= 10005; break;
1635 case wxFONTENCODING_MACGREEK
: ret
= 10006; break;
1636 case wxFONTENCODING_MACCYRILLIC
: ret
= 10007; break;
1637 case wxFONTENCODING_MACTHAI
: ret
= 10021; break;
1638 case wxFONTENCODING_MACCHINESESIMP
: ret
= 10008; break;
1639 case wxFONTENCODING_MACCENTRALEUR
: ret
= 10029; break;
1640 case wxFONTENCODING_MACCROATIAN
: ret
= 10082; break;
1641 case wxFONTENCODING_MACICELANDIC
: ret
= 10079; break;
1642 case wxFONTENCODING_MACROMANIAN
: ret
= 10009; break;
1644 case wxFONTENCODING_ISO2022_JP
: ret
= 50222; break;
1646 case wxFONTENCODING_UTF7
: ret
= 65000; break;
1647 case wxFONTENCODING_UTF8
: ret
= 65001; break;
1652 if (::IsValidCodePage(ret
) == 0)
1656 if (::GetCPInfo(ret
, &info
) == 0)
1662 extern long wxCharsetToCodepage(const char *name
)
1664 // first get the font encoding for this charset
1668 wxFontEncoding enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
1669 if ( enc
== wxFONTENCODING_SYSTEM
)
1672 // the use the helper function
1673 return wxEncodingToCodepage(enc
);
1676 #else // !wxUSE_FONTMAP
1678 #include "wx/msw/registry.h"
1680 // this should work if Internet Exploiter is installed
1681 extern long wxCharsetToCodepage(const char *name
)
1689 wxString
path(wxT("MIME\\Database\\Charset\\"));
1692 // follow the alias loop
1695 wxRegKey
key(wxRegKey::HKCR
, path
+ cn
);
1700 // two cases: either there's an AliasForCharset string,
1701 // or there are Codepage and InternetEncoding dwords.
1702 // The InternetEncoding gives us the actual encoding,
1703 // the Codepage just says which Windows character set to
1704 // use when displaying the data.
1705 if (key
.HasValue(wxT("InternetEncoding")) &&
1706 key
.QueryValue(wxT("InternetEncoding"), &CP
))
1709 // no encoding, see if it's an alias
1710 if (!key
.HasValue(wxT("AliasForCharset")) ||
1711 !key
.QueryValue(wxT("AliasForCharset"), cn
))
1714 #endif // wxUSE_REGKEY
1719 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1721 extern "C" WXDLLIMPEXP_BASE HWND
1722 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
)
1724 wxCHECK_MSG( classname
&& pclassname
&& wndproc
, NULL
,
1725 wxT("NULL parameter in wxCreateHiddenWindow") );
1727 // register the class fi we need to first
1728 if ( *pclassname
== NULL
)
1731 wxZeroMemory(wndclass
);
1733 wndclass
.lpfnWndProc
= wndproc
;
1734 wndclass
.hInstance
= wxGetInstance();
1735 wndclass
.lpszClassName
= classname
;
1737 if ( !::RegisterClass(&wndclass
) )
1739 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1744 *pclassname
= classname
;
1747 // next create the window
1748 HWND hwnd
= ::CreateWindow
1762 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));