Example #1
0
        public static void CreateConsole()
        {
            //(see desmume for the basis of some of this logic)

            if (hasConsole)
            {
                return;
            }

            if (oldOut == IntPtr.Zero)
            {
                oldOut = Win32.GetStdHandle(-11);                   //STD_OUTPUT_HANDLE
            }
            Win32.FileType fileType = Win32.GetFileType(oldOut);

            //stdout is already connected to something. keep using it and dont let the console interfere
            shouldRedirectStdout = (fileType == Win32.FileType.FileTypeUnknown || fileType == Win32.FileType.FileTypePipe);

            //attach to an existing console
            attachedConsole = false;

            //ever since a recent KB, XP-based systems glitch out when attachconsole is called and theres no console to attach to.
            if (Environment.OSVersion.Version.Major != 5)
            {
                if (Win32.AttachConsole(-1))
                {
                    hasConsole      = true;
                    attachedConsole = true;
                }
            }

            if (!attachedConsole)
            {
                Win32.FreeConsole();
                if (Win32.AllocConsole())
                {
                    //set icons for the console so we can tell them apart from the main window
                    Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080 /*WM_SETICON*/, (IntPtr)0 /*ICON_SMALL*/, Properties.Resources.console16x16.GetHicon());
                    Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080 /*WM_SETICON*/, (IntPtr)1 /*ICON_LARGE*/, Properties.Resources.console32x32.GetHicon());
                    hasConsole = true;
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(string.Format("Couldn't allocate win32 console: {0}", Marshal.GetLastWin32Error()));
                }
            }

            if (hasConsole)
            {
                IntPtr ptr         = Win32.GetCommandLine();
                string commandLine = Marshal.PtrToStringAuto(ptr);
                Console.Title = SkipEverythingButProgramInCommandLine(commandLine);
            }

            if (shouldRedirectStdout)
            {
                conOut = Win32.CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);

                if (!Win32.SetStdHandle(-11, conOut))
                {
                    throw new Exception("SetStdHandle() failed");
                }
            }

            //DotNetRewireConout();
            hasConsole = true;

            if (attachedConsole)
            {
                Console.WriteLine();
                Console.WriteLine("use cmd /c {0} to get more sensible console behaviour", Path.GetFileName(PathManager.GetBasePathAbsolute()));
            }
        }