]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
compilation fixes - wxGTK compiles but not links
[wxWidgets.git] / src / msw / utils.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utils.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/cursor.h"
35 #include "wx/intl.h"
36 #include "wx/log.h"
37 #endif //WX_PRECOMP
38
39 // In some mingws there is a missing extern "C" int the winsock header,
40 // so we put it here just to be safe. Note that this must appear _before_
41 // #include "wx/msw/private.h" which itself includes <windows.h>, as this
42 // one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
43 //
44 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
45 extern "C" {
46 #include <winsock.h> // we use socket functions in wxGetFullHostName()
47 }
48 #endif
49
50 #include "wx/msw/private.h" // includes <windows.h>
51
52 #include "wx/timer.h"
53
54 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
55 #include <direct.h>
56
57 #ifndef __MWERKS__
58 #include <dos.h>
59 #endif
60 #endif //GNUWIN32
61
62 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
63 #include <sys/unistd.h>
64 #include <sys/stat.h>
65 #endif //GNUWIN32
66
67 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
68 // this (3.1 I believe) and how to test for it.
69 // If this works for Borland 4.0 as well, then no worries.
70 #include <dir.h>
71 #endif
72
73 // VZ: there is some code using NetXXX() functions to get the full user name:
74 // I don't think it's a good idea because they don't work under Win95 and
75 // seem to return the same as wxGetUserId() under NT. If you really want
76 // to use them, just #define USE_NET_API
77 #undef USE_NET_API
78
79 #ifdef USE_NET_API
80 #include <lm.h>
81 #endif // USE_NET_API
82
83 #if defined(__WIN32__) && !defined(__WXWINE__)
84 #include <io.h>
85
86 #ifndef __GNUWIN32__
87 #include <shellapi.h>
88 #endif
89 #endif
90
91 #ifndef __WATCOMC__
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
93 #include <errno.h>
94 #endif
95 #endif
96
97 //// BEGIN for console support: VC++ only
98 #ifdef __VISUALC__
99
100 #include "wx/msw/msvcrt.h"
101
102 #include <fcntl.h>
103
104 #include "wx/ioswrap.h"
105
106 #include "wx/ioswrap.h"
107
108 /* Need to undef new if including crtdbg.h */
109 # ifdef new
110 # undef new
111 # endif
112
113 #ifndef __WIN16__
114 # include <crtdbg.h>
115 #endif
116
117 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
118 # define new new(__TFILE__,__LINE__)
119 # endif
120
121 #endif
122 // __VISUALC__
123 /// END for console support
124
125 // ----------------------------------------------------------------------------
126 // constants
127 // ----------------------------------------------------------------------------
128
129 // In the WIN.INI file
130 static const wxChar WX_SECTION[] = wxT("wxWindows");
131 static const wxChar eUSERNAME[] = wxT("UserName");
132
133 // these are only used under Win16
134 #ifndef __WIN32__
135 static const wxChar eHOSTNAME[] = wxT("HostName");
136 static const wxChar eUSERID[] = wxT("UserId");
137 #endif // !Win32
138
139 // ============================================================================
140 // implementation
141 // ============================================================================
142
143 // ----------------------------------------------------------------------------
144 // get host name and related
145 // ----------------------------------------------------------------------------
146
147 // Get hostname only (without domain name)
148 bool wxGetHostName(wxChar *buf, int maxSize)
149 {
150 #if defined(__WIN32__) && !defined(__TWIN32__)
151 DWORD nSize = maxSize;
152 if ( !::GetComputerName(buf, &nSize) )
153 {
154 wxLogLastError(wxT("GetComputerName"));
155
156 return FALSE;
157 }
158
159 return TRUE;
160 #else
161 wxChar *sysname;
162 const wxChar *default_host = wxT("noname");
163
164 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
165 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
166 } else
167 wxStrncpy(buf, sysname, maxSize - 1);
168 buf[maxSize] = wxT('\0');
169 return *buf ? TRUE : FALSE;
170 #endif
171 }
172
173 // get full hostname (with domain name if possible)
174 bool wxGetFullHostName(wxChar *buf, int maxSize)
175 {
176 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
177 // TODO should use GetComputerNameEx() when available
178 WSADATA wsa;
179 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
180 {
181 wxString host;
182 char bufA[256];
183 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
184 {
185 // gethostname() won't usually include the DNS domain name, for
186 // this we need to work a bit more
187 if ( !strchr(bufA, '.') )
188 {
189 struct hostent *pHostEnt = gethostbyname(bufA);
190
191 if ( pHostEnt )
192 {
193 // Windows will use DNS internally now
194 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, PF_INET);
195 }
196
197 if ( pHostEnt )
198 {
199 host = pHostEnt->h_name;
200 }
201 }
202 }
203
204 WSACleanup();
205
206 if ( !!host )
207 {
208 wxStrncpy(buf, host, maxSize);
209
210 return TRUE;
211 }
212 }
213 #endif // Win32
214
215 return wxGetHostName(buf, maxSize);
216 }
217
218 // Get user ID e.g. jacs
219 bool wxGetUserId(wxChar *buf, int maxSize)
220 {
221 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__)
222 DWORD nSize = maxSize;
223 if ( ::GetUserName(buf, &nSize) == 0 )
224 {
225 // actually, it does happen on Win9x if the user didn't log on
226 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
227 if ( res == 0 )
228 {
229 // not found
230 return FALSE;
231 }
232 }
233
234 return TRUE;
235 #else // Win16 or Win32s
236 wxChar *user;
237 const wxChar *default_id = wxT("anonymous");
238
239 // Can't assume we have NIS (PC-NFS) or some other ID daemon
240 // So we ...
241 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
242 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
243 {
244 // Use wxWindows configuration data (comming soon)
245 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
246 }
247 else
248 {
249 wxStrncpy(buf, user, maxSize - 1);
250 }
251
252 return *buf ? TRUE : FALSE;
253 #endif
254 }
255
256 // Get user name e.g. Julian Smart
257 bool wxGetUserName(wxChar *buf, int maxSize)
258 {
259 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
260 extern HANDLE g_hPenWin; // PenWindows Running?
261 if (g_hPenWin)
262 {
263 // PenWindows Does have a user concept!
264 // Get the current owner of the recognizer
265 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
266 strncpy(buf, wxBuffer, maxSize - 1);
267 }
268 else
269 #endif
270 {
271 #ifdef USE_NET_API
272 CHAR szUserName[256];
273 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
274 return FALSE;
275
276 // TODO how to get the domain name?
277 CHAR *szDomain = "";
278
279 // the code is based on the MSDN example (also see KB article Q119670)
280 WCHAR wszUserName[256]; // Unicode user name
281 WCHAR wszDomain[256];
282 LPBYTE ComputerName;
283
284 USER_INFO_2 *ui2; // User structure
285
286 // Convert ANSI user name and domain to Unicode
287 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
288 wszUserName, WXSIZEOF(wszUserName) );
289 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
290 wszDomain, WXSIZEOF(wszDomain) );
291
292 // Get the computer name of a DC for the domain.
293 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
294 {
295 wxLogError(wxT("Can not find domain controller"));
296
297 goto error;
298 }
299
300 // Look up the user on the DC
301 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
302 (LPWSTR)&wszUserName,
303 2, // level - we want USER_INFO_2
304 (LPBYTE *) &ui2 );
305 switch ( status )
306 {
307 case NERR_Success:
308 // ok
309 break;
310
311 case NERR_InvalidComputer:
312 wxLogError(wxT("Invalid domain controller name."));
313
314 goto error;
315
316 case NERR_UserNotFound:
317 wxLogError(wxT("Invalid user name '%s'."), szUserName);
318
319 goto error;
320
321 default:
322 wxLogSysError(wxT("Can't get information about user"));
323
324 goto error;
325 }
326
327 // Convert the Unicode full name to ANSI
328 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
329 buf, maxSize, NULL, NULL );
330
331 return TRUE;
332
333 error:
334 wxLogError(wxT("Couldn't look up full user name."));
335
336 return FALSE;
337 #else // !USE_NET_API
338 // Could use NIS, MS-Mail or other site specific programs
339 // Use wxWindows configuration data
340 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxT(""), buf, maxSize - 1) != 0;
341 if ( !ok )
342 {
343 ok = wxGetUserId(buf, maxSize);
344 }
345
346 if ( !ok )
347 {
348 wxStrncpy(buf, wxT("Unknown User"), maxSize);
349 }
350 #endif // Win32/16
351 }
352
353 return TRUE;
354 }
355
356 const wxChar* wxGetHomeDir(wxString *pstr)
357 {
358 wxString& strDir = *pstr;
359
360 #if defined(__UNIX__) && !defined(__TWIN32__)
361 const wxChar *szHome = wxGetenv("HOME");
362 if ( szHome == NULL ) {
363 // we're homeless...
364 wxLogWarning(_("can't find user's HOME, using current directory."));
365 strDir = wxT(".");
366 }
367 else
368 strDir = szHome;
369
370 // add a trailing slash if needed
371 if ( strDir.Last() != wxT('/') )
372 strDir << wxT('/');
373 #else // Windows
374 #ifdef __WIN32__
375 const wxChar *szHome = wxGetenv(wxT("HOMEDRIVE"));
376 if ( szHome != NULL )
377 strDir << szHome;
378 szHome = wxGetenv(wxT("HOMEPATH"));
379 if ( szHome != NULL ) {
380 strDir << szHome;
381
382 // the idea is that under NT these variables have default values
383 // of "%systemdrive%:" and "\\". As we don't want to create our
384 // config files in the root directory of the system drive, we will
385 // create it in our program's dir. However, if the user took care
386 // to set HOMEPATH to something other than "\\", we suppose that he
387 // knows what he is doing and use the supplied value.
388 if ( wxStrcmp(szHome, wxT("\\")) != 0 )
389 return strDir.c_str();
390 }
391
392 #else // Win16
393 // Win16 has no idea about home, so use the working directory instead
394 #endif // WIN16/32
395
396 // 260 was taken from windef.h
397 #ifndef MAX_PATH
398 #define MAX_PATH 260
399 #endif
400
401 wxString strPath;
402 ::GetModuleFileName(::GetModuleHandle(NULL),
403 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
404 strPath.UngetWriteBuf();
405
406 // extract the dir name
407 wxSplitPath(strPath, &strDir, NULL, NULL);
408
409 #endif // UNIX/Win
410
411 return strDir.c_str();
412 }
413
414 wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
415 {
416 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
417 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
418 // static buffer and sometimes I don't even know what.
419 static wxString s_home;
420
421 return (wxChar *)wxGetHomeDir(&s_home);
422 }
423
424 bool wxDirExists(const wxString& dir)
425 {
426 #if defined(__WIN32__)
427 DWORD attribs = GetFileAttributes(dir);
428 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
429 #else // Win16
430 #ifdef __BORLANDC__
431 struct ffblk fileInfo;
432 #else
433 struct find_t fileInfo;
434 #endif
435 // In Borland findfirst has a different argument
436 // ordering from _dos_findfirst. But _dos_findfirst
437 // _should_ be ok in both MS and Borland... why not?
438 #ifdef __BORLANDC__
439 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
440 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
441 #else
442 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
443 ((fileInfo.attrib & _A_SUBDIR) != 0);
444 #endif
445 #endif // Win32/16
446 }
447
448 // ----------------------------------------------------------------------------
449 // env vars
450 // ----------------------------------------------------------------------------
451
452 bool wxGetEnv(const wxString& var, wxString *value)
453 {
454 #ifdef __WIN16__
455 const wxChar* ret = wxGetenv(var);
456 if (ret)
457 {
458 *value = ret;
459 return TRUE;
460 }
461 else
462 return FALSE;
463 #else
464 // first get the size of the buffer
465 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
466 if ( !dwRet )
467 {
468 // this means that there is no such variable
469 return FALSE;
470 }
471
472 if ( value )
473 {
474 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
475 value->UngetWriteBuf();
476 }
477
478 return TRUE;
479 #endif
480 }
481
482 bool wxSetEnv(const wxString& var, const wxChar *value)
483 {
484 // some compilers have putenv() or _putenv() or _wputenv() but it's better
485 // to always use Win32 function directly instead of dealing with them
486 #if defined(__WIN32__)
487 if ( !::SetEnvironmentVariable(var, value) )
488 {
489 wxLogLastError(_T("SetEnvironmentVariable"));
490
491 return FALSE;
492 }
493
494 return TRUE;
495 #else // no way to set env vars
496 return FALSE;
497 #endif
498 }
499
500 // ----------------------------------------------------------------------------
501 // process management
502 // ----------------------------------------------------------------------------
503
504 #ifdef __WIN32__
505
506 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
507 struct wxFindByPidParams
508 {
509 wxFindByPidParams() { hwnd = 0; pid = 0; }
510
511 // the HWND used to return the result
512 HWND hwnd;
513
514 // the PID we're looking from
515 DWORD pid;
516 };
517
518 // wxKill helper: EnumWindows() callback which is used to find the first (top
519 // level) window belonging to the given process
520 BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
521 {
522 DWORD pid;
523 (void)::GetWindowThreadProcessId(hwnd, &pid);
524
525 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
526 if ( pid == params->pid )
527 {
528 // remember the window we found
529 params->hwnd = hwnd;
530
531 // return FALSE to stop the enumeration
532 return FALSE;
533 }
534
535 // continue enumeration
536 return TRUE;
537 }
538
539 #endif // __WIN32__
540
541 int wxKill(long pid, wxSignal sig, wxKillError *krc)
542 {
543 #ifdef __WIN32__
544 // get the process handle to operate on
545 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
546 PROCESS_TERMINATE |
547 PROCESS_QUERY_INFORMATION,
548 FALSE, // not inheritable
549 (DWORD)pid);
550 if ( hProcess == NULL )
551 {
552 if ( krc )
553 {
554 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
555 {
556 *krc = wxKILL_ACCESS_DENIED;
557 }
558 else
559 {
560 *krc = wxKILL_NO_PROCESS;
561 }
562 }
563
564 return -1;
565 }
566
567 bool ok = TRUE;
568 switch ( sig )
569 {
570 case wxSIGKILL:
571 // kill the process forcefully returning -1 as error code
572 if ( !::TerminateProcess(hProcess, (UINT)-1) )
573 {
574 wxLogSysError(_("Failed to kill process %d"), pid);
575
576 if ( krc )
577 {
578 // this is not supposed to happen if we could open the
579 // process
580 *krc = wxKILL_ERROR;
581 }
582
583 ok = FALSE;
584 }
585 break;
586
587 case wxSIGNONE:
588 // do nothing, we just want to test for process existence
589 break;
590
591 default:
592 // any other signal means "terminate"
593 {
594 wxFindByPidParams params;
595 params.pid = (DWORD)pid;
596
597 // EnumWindows() has nice semantics: it returns 0 if it found
598 // something or if an error occured and non zero if it
599 // enumerated all the window
600 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
601 {
602 // did we find any window?
603 if ( params.hwnd )
604 {
605 // tell the app to close
606 //
607 // NB: this is the harshest way, the app won't have
608 // opportunity to save any files, for example, but
609 // this is probably what we want here. If not we
610 // can also use SendMesageTimeout(WM_CLOSE)
611 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
612 {
613 wxLogLastError(_T("PostMessage(WM_QUIT)"));
614 }
615 }
616 else // it was an error then
617 {
618 wxLogLastError(_T("EnumWindows"));
619
620 ok = FALSE;
621 }
622 }
623 else // no windows for this PID
624 {
625 if ( krc )
626 {
627 *krc = wxKILL_ERROR;
628 }
629
630 ok = FALSE;
631 }
632 }
633 }
634
635 // the return code
636 DWORD rc;
637
638 if ( ok )
639 {
640 // as we wait for a short time, we can use just WaitForSingleObject()
641 // and not MsgWaitForMultipleObjects()
642 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
643 {
644 case WAIT_OBJECT_0:
645 // process terminated
646 if ( !::GetExitCodeProcess(hProcess, &rc) )
647 {
648 wxLogLastError(_T("GetExitCodeProcess"));
649 }
650 break;
651
652 default:
653 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
654 // fall through
655
656 case WAIT_FAILED:
657 wxLogLastError(_T("WaitForSingleObject"));
658 // fall through
659
660 case WAIT_TIMEOUT:
661 if ( krc )
662 {
663 *krc = wxKILL_ERROR;
664 }
665
666 rc = STILL_ACTIVE;
667 break;
668 }
669 }
670 else // !ok
671 {
672 // just to suppress the warnings about uninitialized variable
673 rc = 0;
674 }
675
676 ::CloseHandle(hProcess);
677
678 // the return code is the same as from Unix kill(): 0 if killed
679 // successfully or -1 on error
680 if ( sig == wxSIGNONE )
681 {
682 if ( ok && rc == STILL_ACTIVE )
683 {
684 // there is such process => success
685 return 0;
686 }
687 }
688 else // not SIGNONE
689 {
690 if ( ok && rc != STILL_ACTIVE )
691 {
692 // killed => success
693 return 0;
694 }
695 }
696 #else // Win15
697 wxFAIL_MSG( _T("not implemented") );
698 #endif // Win32/Win16
699
700 // error
701 return -1;
702 }
703
704 // Execute a program in an Interactive Shell
705 bool wxShell(const wxString& command)
706 {
707 wxChar *shell = wxGetenv(wxT("COMSPEC"));
708 if ( !shell )
709 shell = wxT("\\COMMAND.COM");
710
711 wxString cmd;
712 if ( !command )
713 {
714 // just the shell
715 cmd = shell;
716 }
717 else
718 {
719 // pass the command to execute to the command processor
720 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
721 }
722
723 return wxExecute(cmd, TRUE /* sync */) != 0;
724 }
725
726 // ----------------------------------------------------------------------------
727 // misc
728 // ----------------------------------------------------------------------------
729
730 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
731 long wxGetFreeMemory()
732 {
733 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
734 MEMORYSTATUS memStatus;
735 memStatus.dwLength = sizeof(MEMORYSTATUS);
736 GlobalMemoryStatus(&memStatus);
737 return memStatus.dwAvailPhys;
738 #else
739 return (long)GetFreeSpace(0);
740 #endif
741 }
742
743 // Emit a beeeeeep
744 void wxBell()
745 {
746 ::MessageBeep((UINT)-1); // default sound
747 }
748
749 wxString wxGetOsDescription()
750 {
751 #ifdef __WIN32__
752 wxString str;
753
754 OSVERSIONINFO info;
755 wxZeroMemory(info);
756
757 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
758 if ( ::GetVersionEx(&info) )
759 {
760 switch ( info.dwPlatformId )
761 {
762 case VER_PLATFORM_WIN32s:
763 str = _("Win32s on Windows 3.1");
764 break;
765
766 case VER_PLATFORM_WIN32_WINDOWS:
767 str.Printf(_("Windows 9%c"),
768 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
769 if ( !wxIsEmpty(info.szCSDVersion) )
770 {
771 str << _T(" (") << info.szCSDVersion << _T(')');
772 }
773 break;
774
775 case VER_PLATFORM_WIN32_NT:
776 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
777 info.dwMajorVersion,
778 info.dwMinorVersion,
779 info.dwBuildNumber);
780 if ( !wxIsEmpty(info.szCSDVersion) )
781 {
782 str << _T(", ") << info.szCSDVersion;
783 }
784 str << _T(')');
785 break;
786 }
787 }
788 else
789 {
790 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
791 }
792
793 return str;
794 #else // Win16
795 return _("Windows 3.1");
796 #endif // Win32/16
797 }
798
799 int wxGetOsVersion(int *majorVsn, int *minorVsn)
800 {
801 #if defined(__WIN32__) && !defined(__SC__)
802 OSVERSIONINFO info;
803 wxZeroMemory(info);
804
805 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
806 if ( ::GetVersionEx(&info) )
807 {
808 if (majorVsn)
809 *majorVsn = info.dwMajorVersion;
810 if (minorVsn)
811 *minorVsn = info.dwMinorVersion;
812
813 switch ( info.dwPlatformId )
814 {
815 case VER_PLATFORM_WIN32s:
816 return wxWIN32S;
817
818 case VER_PLATFORM_WIN32_WINDOWS:
819 return wxWIN95;
820
821 case VER_PLATFORM_WIN32_NT:
822 return wxWINDOWS_NT;
823 }
824 }
825
826 return wxWINDOWS; // error if we get here, return generic value
827 #else // Win16
828 int retValue = wxWINDOWS;
829 #ifdef __WINDOWS_386__
830 retValue = wxWIN386;
831 #else
832 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
833 extern HANDLE g_hPenWin;
834 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
835 #endif
836 #endif
837
838 if (majorVsn)
839 *majorVsn = 3;
840 if (minorVsn)
841 *minorVsn = 1;
842
843 return retValue;
844 #endif
845 }
846
847 // ----------------------------------------------------------------------------
848 // sleep functions
849 // ----------------------------------------------------------------------------
850
851 #if wxUSE_GUI
852
853 #if wxUSE_TIMER
854
855 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
856 static bool gs_inTimer = FALSE;
857
858 class wxSleepTimer : public wxTimer
859 {
860 public:
861 virtual void Notify()
862 {
863 gs_inTimer = FALSE;
864 Stop();
865 }
866 };
867
868 static wxTimer *wxTheSleepTimer = NULL;
869
870 void wxUsleep(unsigned long milliseconds)
871 {
872 #ifdef __WIN32__
873 ::Sleep(milliseconds);
874 #else // !Win32
875 if (gs_inTimer)
876 return;
877
878 wxTheSleepTimer = new wxSleepTimer;
879 gs_inTimer = TRUE;
880 wxTheSleepTimer->Start(milliseconds);
881 while (gs_inTimer)
882 {
883 if (wxTheApp->Pending())
884 wxTheApp->Dispatch();
885 }
886 delete wxTheSleepTimer;
887 wxTheSleepTimer = NULL;
888 #endif // Win32/!Win32
889 }
890
891 void wxSleep(int nSecs)
892 {
893 if (gs_inTimer)
894 return;
895
896 wxTheSleepTimer = new wxSleepTimer;
897 gs_inTimer = TRUE;
898 wxTheSleepTimer->Start(nSecs*1000);
899 while (gs_inTimer)
900 {
901 if (wxTheApp->Pending())
902 wxTheApp->Dispatch();
903 }
904 delete wxTheSleepTimer;
905 wxTheSleepTimer = NULL;
906 }
907
908 // Consume all events until no more left
909 void wxFlushEvents()
910 {
911 // wxYield();
912 }
913
914 #endif // wxUSE_TIMER
915
916 #elif defined(__WIN32__) // wxUSE_GUI
917
918 void wxUsleep(unsigned long milliseconds)
919 {
920 ::Sleep(milliseconds);
921 }
922
923 void wxSleep(int nSecs)
924 {
925 wxUsleep(1000*nSecs);
926 }
927
928 #endif // wxUSE_GUI/!wxUSE_GUI
929
930 // ----------------------------------------------------------------------------
931 // deprecated (in favour of wxLog) log functions
932 // ----------------------------------------------------------------------------
933
934 #if wxUSE_GUI
935
936 // Output a debug mess., in a system dependent fashion.
937 void wxDebugMsg(const wxChar *fmt ...)
938 {
939 va_list ap;
940 static wxChar buffer[512];
941
942 if (!wxTheApp->GetWantDebugOutput())
943 return ;
944
945 va_start(ap, fmt);
946
947 wvsprintf(buffer,fmt,ap) ;
948 OutputDebugString((LPCTSTR)buffer) ;
949
950 va_end(ap);
951 }
952
953 // Non-fatal error: pop up message box and (possibly) continue
954 void wxError(const wxString& msg, const wxString& title)
955 {
956 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
957 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
958 MB_ICONSTOP | MB_YESNO) == IDNO)
959 wxExit();
960 }
961
962 // Fatal error: pop up message box and abort
963 void wxFatalError(const wxString& msg, const wxString& title)
964 {
965 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
966 FatalAppExit(0, (LPCTSTR)wxBuffer);
967 }
968
969 // ----------------------------------------------------------------------------
970 // functions to work with .INI files
971 // ----------------------------------------------------------------------------
972
973 // Reading and writing resources (eg WIN.INI, .Xdefaults)
974 #if wxUSE_RESOURCES
975 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
976 {
977 if (file != wxT(""))
978 // Don't know what the correct cast should be, but it doesn't
979 // compile in BC++/16-bit without this cast.
980 #if !defined(__WIN32__)
981 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
982 #else
983 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
984 #endif
985 else
986 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
987 }
988
989 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
990 {
991 wxString buf;
992 buf.Printf(wxT("%.4f"), value);
993
994 return wxWriteResource(section, entry, buf, file);
995 }
996
997 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
998 {
999 wxString buf;
1000 buf.Printf(wxT("%ld"), value);
1001
1002 return wxWriteResource(section, entry, buf, file);
1003 }
1004
1005 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
1006 {
1007 wxString buf;
1008 buf.Printf(wxT("%d"), value);
1009
1010 return wxWriteResource(section, entry, buf, file);
1011 }
1012
1013 bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
1014 {
1015 static const wxChar defunkt[] = wxT("$$default");
1016 if (file != wxT(""))
1017 {
1018 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1019 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
1020 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1021 return FALSE;
1022 }
1023 else
1024 {
1025 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1026 (LPTSTR)wxBuffer, 1000);
1027 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1028 return FALSE;
1029 }
1030 if (*value) delete[] (*value);
1031 *value = copystring(wxBuffer);
1032 return TRUE;
1033 }
1034
1035 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
1036 {
1037 wxChar *s = NULL;
1038 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1039 if (succ)
1040 {
1041 *value = (float)wxStrtod(s, NULL);
1042 delete[] s;
1043 return TRUE;
1044 }
1045 else return FALSE;
1046 }
1047
1048 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
1049 {
1050 wxChar *s = NULL;
1051 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1052 if (succ)
1053 {
1054 *value = wxStrtol(s, NULL, 10);
1055 delete[] s;
1056 return TRUE;
1057 }
1058 else return FALSE;
1059 }
1060
1061 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
1062 {
1063 wxChar *s = NULL;
1064 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1065 if (succ)
1066 {
1067 *value = (int)wxStrtol(s, NULL, 10);
1068 delete[] s;
1069 return TRUE;
1070 }
1071 else return FALSE;
1072 }
1073 #endif // wxUSE_RESOURCES
1074
1075 // ---------------------------------------------------------------------------
1076 // helper functions for showing a "busy" cursor
1077 // ---------------------------------------------------------------------------
1078
1079 static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
1080 static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
1081 static int gs_wxBusyCursorCount = 0;
1082
1083 extern HCURSOR wxGetCurrentBusyCursor()
1084 {
1085 return gs_wxBusyCursor;
1086 }
1087
1088 // Set the cursor to the busy cursor for all windows
1089 void wxBeginBusyCursor(wxCursor *cursor)
1090 {
1091 if ( gs_wxBusyCursorCount++ == 0 )
1092 {
1093 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
1094 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
1095 }
1096 //else: nothing to do, already set
1097 }
1098
1099 // Restore cursor to normal
1100 void wxEndBusyCursor()
1101 {
1102 wxCHECK_RET( gs_wxBusyCursorCount > 0,
1103 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1104
1105 if ( --gs_wxBusyCursorCount == 0 )
1106 {
1107 ::SetCursor(gs_wxBusyCursorOld);
1108
1109 gs_wxBusyCursorOld = 0;
1110 }
1111 }
1112
1113 // TRUE if we're between the above two calls
1114 bool wxIsBusy()
1115 {
1116 return (gs_wxBusyCursorCount > 0);
1117 }
1118
1119 // Check whether this window wants to process messages, e.g. Stop button
1120 // in long calculations.
1121 bool wxCheckForInterrupt(wxWindow *wnd)
1122 {
1123 wxCHECK( wnd, FALSE );
1124
1125 MSG msg;
1126 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
1127 {
1128 ::TranslateMessage(&msg);
1129 ::DispatchMessage(&msg);
1130 }
1131
1132 return TRUE;
1133 }
1134
1135 // MSW only: get user-defined resource from the .res file.
1136 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1137
1138 wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
1139 {
1140 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
1141 if ( hResource == 0 )
1142 return NULL;
1143
1144 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
1145 if ( hData == 0 )
1146 return NULL;
1147
1148 wxChar *theText = (wxChar *)::LockResource(hData);
1149 if ( !theText )
1150 return NULL;
1151
1152 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1153 // so we need to find the length of the resource.
1154 int len = ::SizeofResource(wxGetInstance(), hResource);
1155 wxChar *s = new wxChar[len+1];
1156 wxStrncpy(s,theText,len);
1157 s[len]=0;
1158
1159 // wxChar *s = copystring(theText);
1160
1161 // Obsolete in WIN32
1162 #ifndef __WIN32__
1163 UnlockResource(hData);
1164 #endif
1165
1166 // No need??
1167 // GlobalFree(hData);
1168
1169 return s;
1170 }
1171
1172 // ----------------------------------------------------------------------------
1173 // get display info
1174 // ----------------------------------------------------------------------------
1175
1176 // See also the wxGetMousePosition in window.cpp
1177 // Deprecated: use wxPoint wxGetMousePosition() instead
1178 void wxGetMousePosition( int* x, int* y )
1179 {
1180 POINT pt;
1181 GetCursorPos( & pt );
1182 if ( x ) *x = pt.x;
1183 if ( y ) *y = pt.y;
1184 };
1185
1186 // Return TRUE if we have a colour display
1187 bool wxColourDisplay()
1188 {
1189 // this function is called from wxDC ctor so it is called a *lot* of times
1190 // hence we optimize it a bit but doign the check only once
1191 //
1192 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1193 // can call us
1194 static int s_isColour = -1;
1195
1196 if ( s_isColour == -1 )
1197 {
1198 ScreenHDC dc;
1199 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1200
1201 s_isColour = (noCols == -1) || (noCols > 2);
1202 }
1203
1204 return s_isColour != 0;
1205 }
1206
1207 // Returns depth of screen
1208 int wxDisplayDepth()
1209 {
1210 ScreenHDC dc;
1211 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
1212 }
1213
1214 // Get size of display
1215 void wxDisplaySize(int *width, int *height)
1216 {
1217 ScreenHDC dc;
1218
1219 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
1220 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
1221 }
1222
1223 void wxDisplaySizeMM(int *width, int *height)
1224 {
1225 ScreenHDC dc;
1226
1227 if ( width ) *width = GetDeviceCaps(dc, HORZSIZE);
1228 if ( height ) *height = GetDeviceCaps(dc, VERTSIZE);
1229 }
1230
1231 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1232 {
1233 #ifdef __WIN16__
1234 *x = 0; *y = 0;
1235 wxDisplaySize(width, height);
1236 #else
1237 // Determine the desktop dimensions minus the taskbar and any other
1238 // special decorations...
1239 RECT r;
1240
1241 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1242 if (x) *x = r.left;
1243 if (y) *y = r.top;
1244 if (width) *width = r.right - r.left;
1245 if (height) *height = r.bottom - r.top;
1246 #endif
1247 }
1248
1249
1250 // ---------------------------------------------------------------------------
1251 // window information functions
1252 // ---------------------------------------------------------------------------
1253
1254 wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1255 {
1256 wxString str;
1257 int len = GetWindowTextLength((HWND)hWnd) + 1;
1258 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1259 str.UngetWriteBuf();
1260
1261 return str;
1262 }
1263
1264 wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1265 {
1266 wxString str;
1267
1268 int len = 256; // some starting value
1269
1270 for ( ;; )
1271 {
1272 // as we've #undefined GetClassName we must now manually choose the
1273 // right function to call
1274 int count =
1275
1276 #ifndef __WIN32__
1277 GetClassName
1278 #else // Win32
1279 #ifdef UNICODE
1280 GetClassNameW
1281 #else // !Unicode
1282 #ifdef __TWIN32__
1283 GetClassName
1284 #else // !Twin32
1285 GetClassNameA
1286 #endif // Twin32/!Twin32
1287 #endif // Unicode/ANSI
1288 #endif // Win16/32
1289 ((HWND)hWnd, str.GetWriteBuf(len), len);
1290
1291 str.UngetWriteBuf();
1292 if ( count == len )
1293 {
1294 // the class name might have been truncated, retry with larger
1295 // buffer
1296 len *= 2;
1297 }
1298 else
1299 {
1300 break;
1301 }
1302 }
1303
1304 return str;
1305 }
1306
1307 WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1308 {
1309 #ifndef __WIN32__
1310 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
1311 #else // Win32
1312 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
1313 #endif // Win16/32
1314 }
1315
1316 #endif // wxUSE_GUI
1317
1318 #if wxUSE_GUI
1319
1320 // ----------------------------------------------------------------------------
1321 // Metafile helpers
1322 // ----------------------------------------------------------------------------
1323
1324 extern void PixelToHIMETRIC(LONG *x, LONG *y)
1325 {
1326 ScreenHDC hdcRef;
1327
1328 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1329 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1330 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1331 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1332
1333 *x *= (iWidthMM * 100);
1334 *x /= iWidthPels;
1335 *y *= (iHeightMM * 100);
1336 *y /= iHeightPels;
1337 }
1338
1339 extern void HIMETRICToPixel(LONG *x, LONG *y)
1340 {
1341 ScreenHDC hdcRef;
1342
1343 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1344 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1345 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1346 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1347
1348 *x *= iWidthPels;
1349 *x /= (iWidthMM * 100);
1350 *y *= iHeightPels;
1351 *y /= (iHeightMM * 100);
1352 }
1353
1354 #endif // wxUSE_GUI
1355
1356 #if 0
1357 //------------------------------------------------------------------------
1358 // wild character routines
1359 //------------------------------------------------------------------------
1360
1361 bool wxIsWild( const wxString& pattern )
1362 {
1363 wxString tmp = pattern;
1364 char *pat = WXSTRINGCAST(tmp);
1365 while (*pat) {
1366 switch (*pat++) {
1367 case '?': case '*': case '[': case '{':
1368 return TRUE;
1369 case '\\':
1370 if (!*pat++)
1371 return FALSE;
1372 }
1373 }
1374 return FALSE;
1375 };
1376
1377
1378 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1379 {
1380 wxString tmp1 = pat;
1381 char *pattern = WXSTRINGCAST(tmp1);
1382 wxString tmp2 = text;
1383 char *str = WXSTRINGCAST(tmp2);
1384 char c;
1385 char *cp;
1386 bool done = FALSE, ret_code, ok;
1387 // Below is for vi fans
1388 const char OB = '{', CB = '}';
1389
1390 // dot_special means '.' only matches '.'
1391 if (dot_special && *str == '.' && *pattern != *str)
1392 return FALSE;
1393
1394 while ((*pattern != '\0') && (!done)
1395 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1396 switch (*pattern) {
1397 case '\\':
1398 pattern++;
1399 if (*pattern != '\0')
1400 pattern++;
1401 break;
1402 case '*':
1403 pattern++;
1404 ret_code = FALSE;
1405 while ((*str!='\0')
1406 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1407 /*loop*/;
1408 if (ret_code) {
1409 while (*str != '\0')
1410 str++;
1411 while (*pattern != '\0')
1412 pattern++;
1413 }
1414 break;
1415 case '[':
1416 pattern++;
1417 repeat:
1418 if ((*pattern == '\0') || (*pattern == ']')) {
1419 done = TRUE;
1420 break;
1421 }
1422 if (*pattern == '\\') {
1423 pattern++;
1424 if (*pattern == '\0') {
1425 done = TRUE;
1426 break;
1427 }
1428 }
1429 if (*(pattern + 1) == '-') {
1430 c = *pattern;
1431 pattern += 2;
1432 if (*pattern == ']') {
1433 done = TRUE;
1434 break;
1435 }
1436 if (*pattern == '\\') {
1437 pattern++;
1438 if (*pattern == '\0') {
1439 done = TRUE;
1440 break;
1441 }
1442 }
1443 if ((*str < c) || (*str > *pattern)) {
1444 pattern++;
1445 goto repeat;
1446 }
1447 } else if (*pattern != *str) {
1448 pattern++;
1449 goto repeat;
1450 }
1451 pattern++;
1452 while ((*pattern != ']') && (*pattern != '\0')) {
1453 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1454 pattern++;
1455 pattern++;
1456 }
1457 if (*pattern != '\0') {
1458 pattern++, str++;
1459 }
1460 break;
1461 case '?':
1462 pattern++;
1463 str++;
1464 break;
1465 case OB:
1466 pattern++;
1467 while ((*pattern != CB) && (*pattern != '\0')) {
1468 cp = str;
1469 ok = TRUE;
1470 while (ok && (*cp != '\0') && (*pattern != '\0')
1471 && (*pattern != ',') && (*pattern != CB)) {
1472 if (*pattern == '\\')
1473 pattern++;
1474 ok = (*pattern++ == *cp++);
1475 }
1476 if (*pattern == '\0') {
1477 ok = FALSE;
1478 done = TRUE;
1479 break;
1480 } else if (ok) {
1481 str = cp;
1482 while ((*pattern != CB) && (*pattern != '\0')) {
1483 if (*++pattern == '\\') {
1484 if (*++pattern == CB)
1485 pattern++;
1486 }
1487 }
1488 } else {
1489 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1490 if (*++pattern == '\\') {
1491 if (*++pattern == CB || *pattern == ',')
1492 pattern++;
1493 }
1494 }
1495 }
1496 if (*pattern != '\0')
1497 pattern++;
1498 }
1499 break;
1500 default:
1501 if (*str == *pattern) {
1502 str++, pattern++;
1503 } else {
1504 done = TRUE;
1505 }
1506 }
1507 }
1508 while (*pattern == '*')
1509 pattern++;
1510 return ((*str == '\0') && (*pattern == '\0'));
1511 };
1512
1513 #endif // 0
1514
1515 #if 0
1516
1517 // maximum mumber of lines the output console should have
1518 static const WORD MAX_CONSOLE_LINES = 500;
1519
1520 BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
1521 FreeConsole();
1522 return TRUE;
1523 }
1524
1525 void wxRedirectIOToConsole()
1526 {
1527 int hConHandle;
1528 long lStdHandle;
1529 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1530 FILE *fp;
1531
1532 // allocate a console for this app
1533 AllocConsole();
1534
1535 // set the screen buffer to be big enough to let us scroll text
1536 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
1537 &coninfo);
1538 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
1539 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
1540 coninfo.dwSize);
1541
1542 // redirect unbuffered STDOUT to the console
1543 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1544 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1545 if(hConHandle <= 0) return;
1546 fp = _fdopen( hConHandle, "w" );
1547 *stdout = *fp;
1548 setvbuf( stdout, NULL, _IONBF, 0 );
1549
1550 // redirect unbuffered STDIN to the console
1551 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1552 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1553 if(hConHandle <= 0) return;
1554 fp = _fdopen( hConHandle, "r" );
1555 *stdin = *fp;
1556 setvbuf( stdin, NULL, _IONBF, 0 );
1557
1558 // redirect unbuffered STDERR to the console
1559 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1560 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1561 if(hConHandle <= 0) return;
1562 fp = _fdopen( hConHandle, "w" );
1563 *stderr = *fp;
1564 setvbuf( stderr, NULL, _IONBF, 0 );
1565
1566 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1567 // point to console as well
1568 ios::sync_with_stdio();
1569
1570 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
1571 }
1572 #else
1573 // Not supported
1574 void wxRedirectIOToConsole()
1575 {
1576 }
1577 #endif
1578
1579