Exemplo n.º 1
0
 /// <summary>
 /// Sets the active console screen buffer to the buffer referrenced by the sb parameter
 /// </summary>
 /// <param name="sb">The screen buffer that will become the active screen buffer.</param>
 public static void SetActiveScreenBuffer(ConsoleScreenBuffer sb)
 {
     if (!WinCon.SetConsoleActiveScreenBuffer(sb.Handle))
     {
         throw new IOException("Error setting active screen buffer.", Marshal.GetLastWin32Error());
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieves the names of all executable files that have defined console aliases.
        /// </summary>
        /// <returns>A StringCollection that contains one entry for each executable
        /// file that has console aliases.</returns>
        public static StringCollection GetAliasExes()
        {
            StringCollection strings = new StringCollection();

            int length = GetAliasExesLength();

            if (length > 0)
            {
                char[] buff = new char[length];
                if (WinCon.GetConsoleAliasExes(buff, length) == 0)
                {
                    throw new IOException("Unable to get alias exes", Marshal.GetLastWin32Error());
                }
                // we have a buffer of nul-terminated strings
                // create individual strings
                int startIndex = 0;
                for (int i = 0; i < length; i++)
                {
                    if (buff[i] == '\0')
                    {
                        string s = new string(buff, startIndex, i - startIndex);
                        strings.Add(s);
                        startIndex = i + 1;
                    }
                }
            }
            return(strings);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Add a console alias string and target text.
 /// </summary>
 /// <param name="Source">The source text.</param>
 /// <param name="Target">The target (replacement) text.</param>
 /// <param name="ExeName">The name of the executable file for which the alias is
 /// to be defined.</param>
 public static void AddAlias(string Source, string Target, string ExeName)
 {
     if (!WinCon.AddConsoleAlias(Source, Target, ExeName))
     {
         throw new IOException("Unable to add alias", Marshal.GetLastWin32Error());
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the list of processes that are attached to the console.
        /// </summary>
        /// <returns>Returns an array of integer process ids.</returns>
        public static int[] GetProcessList()
        {
            int[] processes = new int[10];
            do
            {
                int rslt = WinCon.GetConsoleProcessList(processes, processes.Length);
                if (rslt == 0)
                {
                    throw new IOException("Unable to get process list", Marshal.GetLastWin32Error());
                }
                if (rslt <= processes.Length)
                {
                    // if the array is exactly the right size, return it
                    if (rslt == processes.Length)
                    {
                        return(processes);
                    }

                    // otherwise create a new array of the required length
                    int[] newProcesses = new int[rslt];
                    Array.Copy(processes, newProcesses, rslt);
                    return(newProcesses);
                }
                else
                {
                    // The initial array was too small.
                    // Allocate more space and try again.
                    processes = new int[rslt];
                }
            } while (true);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Obtains the next character or function key pressed by the user.
        /// The pressed key is optionally displayed in the console window.
        /// </summary>
        /// <param name="intercept">Determines whether to display the pressed key in the console window.
        /// true to not display the pressed key; otherwise, false.</param>
        /// <returns>A ConsoleKeyInfo object that describes the ConsoleKey constant and Unicode
        /// character, if any, that correspond to the pressed console key.></returns>
        public ConsoleKeyInfo ReadKey(bool intercept)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            // @TODO: How to I echo the key?
            ConsoleInputEventInfo[] buff = new ConsoleInputEventInfo[1];
            int  numEvents = 0;
            bool isGood    = false;
            ConsoleKeyEventInfo keyEvent = new ConsoleKeyEventInfo();

            do
            {
                if (!WinCon.ReadConsoleInput(Handle, buff, 1, ref numEvents))
                {
                    throw new IOException("Error reading console.", Marshal.GetLastWin32Error());
                }
                // Make sure it's a key down event and that the key is
                // one of the virtual key codes....
                if (buff[0].EventType == ConsoleInputEventType.KeyEvent)
                {
                    keyEvent = buff[0].KeyEvent;
                    isGood   = keyEvent.KeyDown && (Enum.GetName(typeof(ConsoleKey), (ConsoleKey)keyEvent.VirtualKeyCode) != null);
                }
            } while (!isGood);

            // Create ConsoleKeyInfo from key event
            return(new ConsoleKeyInfo(keyEvent.UnicodeChar,
                                      (ConsoleKey)keyEvent.VirtualKeyCode,
                                      (keyEvent.ControlKeyState & ConsoleControlKeyState.ShiftPressed) != 0,
                                      (keyEvent.ControlKeyState & (ConsoleControlKeyState.RightAltPressed | ConsoleControlKeyState.LeftAltPressed)) != 0,
                                      (keyEvent.ControlKeyState & (ConsoleControlKeyState.RightCtrlPressed | ConsoleControlKeyState.LeftCtrlPressed)) != 0));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Generate a console control event.
 /// </summary>
 /// <param name="eventId">The event to generate.  This must be CtrlC or CtrlBreak.</param>
 /// <param name="processGroupId">In most cases, set to 0 to send the event to
 /// all attached processes.</param>
 public static void GenerateCtrlEvent(ConsoleControlEventType eventId, int processGroupId)
 {
     if (!WinCon.GenerateConsoleCtrlEvent((int)eventId, processGroupId))
     {
         throw new IOException("Error generating event.", Marshal.GetLastWin32Error());
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Sets the current attribute (foreground and background colors) to be used when
 /// writing characters.
 /// </summary>
 /// <param name="attr">The desired output attribute.</param>
 public void SetTextAttribute(ConsoleCharAttribute attr)
 {
     if (!WinCon.SetConsoleTextAttribute(_handle, attr))
     {
         throw new ApplicationException("Unable to set text attribute");
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Attach the calling process to the console of the specified process.
        /// </summary>
        /// <param name="processId">Identifier of the process whose console will be attached.</param>
//		public static void AttachConsole(int processId)
//		{
//			if (!AttachConsole(processId))
//			{
//                int err = Marshal.GetLastWin32Error();
//				throw new IOException(String.Format("Unable to attach console 0x{0,X}", processId), err);
//			}
//            SetupControlHandler();
//		}

        /// <summary>
        /// Detaches the calling process from its console.
        /// </summary>
        public static void FreeConsole()
        {
            ReleaseControlHandler();
            if (!WinCon.FreeConsole())
            {
                throw new IOException("Unable to free console", Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 9
0
 // Install the control handler.
 private static void SetupControlHandler()
 {
     HandlerRoutine = new ConsoleCtrlHandlerDelegate(ControlHandler);
     if (!WinCon.SetConsoleCtrlHandler(HandlerRoutine, true))
     {
         throw new IOException("Unable to set handler routine.", Marshal.GetLastWin32Error());
     }
 }
Exemplo n.º 10
0
 /// <summary>
 /// Allocate a new console for the calling process.
 /// </summary>
 public static void AllocConsole()
 {
     if (!WinCon.AllocConsole())
     {
         throw new IOException("Unable to allocate console", Marshal.GetLastWin32Error());
     }
     SetupControlHandler();
 }
Exemplo n.º 11
0
        private ConsoleSelectionInfo GetSelectionInfo()
        {
            ConsoleSelectionInfo csi = new ConsoleSelectionInfo();

            if (!WinCon.GetConsoleSelectionInfo(csi))
            {
                throw new System.IO.IOException("Unable to get selection info.", Marshal.GetLastWin32Error());
            }
            return(csi);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sets the console display mode.
        /// </summary>
        /// <param name="mode">The desired display mode:  Windowed or Fullscreen.</param>
        public void SetDisplayMode(ConsoleDisplayMode mode)
        {
            Coord newSize = new Coord(0, 0);

            if (!WinCon.SetConsoleDisplayMode(this._handle, (int)mode, ref newSize))
            {
                int err = Marshal.GetLastWin32Error();
                throw new IOException("Unable to set display mode.", err);
            }
        }
Exemplo n.º 13
0
 // Uninstall the control handler.
 private static void ReleaseControlHandler()
 {
     if (HandlerRoutine != null)
     {
         if (!WinCon.SetConsoleCtrlHandler(HandlerRoutine, false))
         {
             throw new IOException("Unable to clear handler routine.", Marshal.GetLastWin32Error());
         }
         HandlerRoutine = null;
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Fills characters at a given cursor position.
        /// </summary>
        /// <param name="c">The character to write.</param>
        /// <param name="numChars">The number of character cells to be filled with the character.</param>
        /// <param name="x">The column position where the fill operation is to start.</param>
        /// <param name="y">The row position where the fill operation is to start.</param>
        /// <returns>The number of character cells in which the character was written.</returns>
        public int FillCharXY(Char c, int numChars, int x, int y)
        {
            Coord pos          = new Coord((short)x, (short)y);
            int   charsWritten = 0;

            if (!WinCon.FillConsoleOutputCharacter(_handle, c, numChars, pos, ref charsWritten))
            {
                throw new ApplicationException("Error writing attributes");
            }
            return(charsWritten);
        }
Exemplo n.º 15
0
 private void SetWindowRect(SmallRect sr, bool bAbsolute)
 {
     if (disposed)
     {
         throw new ObjectDisposedException(this.ToString());
     }
     if (!WinCon.SetConsoleWindowInfo(_handle, bAbsolute, sr))
     {
         int err = Marshal.GetLastWin32Error();
         throw new ApplicationException(String.Format("Unable to set window rect: {0}", err));
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Fills character attributes at a given cursor position.
        /// </summary>
        /// <param name="fgColor">The foreground color to use in the fill.</param>
        /// <param name="bgColor">The background color to use in the fill.</param>
        /// <param name="numAttrs">The number of character cells to be filled with the attribute.</param>
        /// <param name="x">The column position where the fill operation is to start.</param>
        /// <param name="y">The row position where the fill operation is to start.</param>
        /// <returns>The number of character cells in which the attribute was written.</returns>
        public int FillAttributeXY(ConsoleColor fgColor, ConsoleColor bgColor, int numAttrs, int x, int y)
        {
            Coord pos = new Coord((short)x, (short)y);
            ConsoleCharAttribute attr = new ConsoleCharAttribute(fgColor, bgColor);
            int attrsWritten          = 0;

            if (!WinCon.FillConsoleOutputAttribute(_handle, attr, numAttrs, pos, ref attrsWritten))
            {
                throw new ApplicationException("Error writing attributes");
            }
            return(attrsWritten);
        }
Exemplo n.º 17
0
        public void Flush()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            if (!WinCon.FlushConsoleInputBuffer(Handle))
            {
                throw new System.IO.IOException("Error flushing buffer", Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 18
0
        private Coord GetLargestWindowSize()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            Coord size = WinCon.GetLargestConsoleWindowSize(_handle);

            if (size.X == 0 && size.Y == 0)
            {
                throw new ApplicationException("Error getting largest window size");
            }
            return(size);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Create a new instance of the ConsoleScreenBuffer class by creating a new
 /// console screen buffer handle.
 /// </summary>
 public ConsoleScreenBuffer()
 {
     _handle = WinCon.CreateConsoleScreenBuffer(
         WinApi.GENERIC_READ | WinApi.GENERIC_WRITE,
         WinApi.FILE_SHARE_READ | WinApi.FILE_SHARE_WRITE,
         null,
         WinCon.CONSOLE_TEXTMODE_BUFFER,
         IntPtr.Zero);
     if (_handle.ToInt32() == WinApi.INVALID_HANDLE_VALUE)
     {
         throw new IOException("Unable to create screen buffer", Marshal.GetLastWin32Error());
     }
     ownsHandle = true;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Sets the screen buffer size in character columns and rows.
        /// </summary>
        /// <param name="width">Desired width, in character columns, of screen buffer.</param>
        /// <param name="height">Desired height, in character rows, of screen buffer.</param>
        public void SetBufferSize(int width, int height)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            Coord sz = new Coord((short)width, (short)height);

            if (!WinCon.SetConsoleScreenBufferSize(_handle, sz))
            {
                throw new IOException("Unable to set screen buffer size", Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 21
0
        private void SetCursorInfo(bool visible, int size)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            ConsoleCursorInfo cci = new ConsoleCursorInfo(visible, size);

            if (!WinCon.SetConsoleCursorInfo(_handle, cci))
            {
                throw new ApplicationException("Error setting cursor information.");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Sets the cursor row and column position.
        /// </summary>
        /// <param name="x">The new column position of the cursor.</param>
        /// <param name="y">The new row position of the cursor.</param>
        public void SetCursorPosition(int x, int y)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            Coord cursorPos = new Coord((short)x, (short)y);

            if (!WinCon.SetConsoleCursorPosition(_handle, cursorPos))
            {
                throw new ApplicationException("Error setting cursor position");
            }
        }
Exemplo n.º 23
0
        public Coord GetFontSize(bool bMax)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            ConsoleFontInfo cfi = new ConsoleFontInfo();

            if (!WinCon.GetCurrentConsoleFont(_handle, bMax, cfi))
            {
                throw new ApplicationException("Unable to get font information.");
            }
            return(cfi.dwFontSize);
        }
Exemplo n.º 24
0
        private ConsoleCursorInfo GetCursorInfo()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            ConsoleCursorInfo cci = new ConsoleCursorInfo();

            if (!WinCon.GetConsoleCursorInfo(_handle, cci))
            {
                throw new ApplicationException("Error getting cursor information.");
            }
            return(cci);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Writes an array of chars at the current cursor position.
        /// </summary>
        /// <param name="text">An array containing the characters to be written.</param>
        /// <param name="nChars">The number of characters to be written.</param>
        /// <returns>The number of characters written.</returns>
        public int Write(char[] text, int nChars)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            int charsWritten = 0;

            if (!WinCon.WriteConsole(_handle, text, nChars, ref charsWritten, IntPtr.Zero))
            {
                throw new System.IO.IOException("Write error", Marshal.GetLastWin32Error());
            }
            return(charsWritten);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Writes character and attribute information to a rectangular portion of the screen buffer.
        /// </summary>
        /// <param name="buff">The array that contains characters and attributes to be written.</param>
        /// <param name="buffX">Column position of the first character to be written from the array.</param>
        /// <param name="buffY">Row position of the first character to be written from the array.</param>
        /// <param name="left">Column position of the top-left corner of the screen buffer area where characters are to be written.</param>
        /// <param name="top">Row position of the top-left corner of the screen buffer area where characters are to be written.</param>
        /// <param name="right">Column position of the bottom-right corner of the screen buffer area where characters are to be written.</param>
        /// <param name="bottom">Row position of the bottom-right corner of the screen buffer area where characters are to be written.</param>
        public void WriteBlock(ConsoleCharInfo[,] buff, int buffX, int buffY, int left, int top, int right, int bottom)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            Coord     bufferSize  = new Coord((short)buff.GetLength(1), (short)buff.GetLength(0));
            Coord     bufferPos   = new Coord((short)buffX, (short)buffY);
            SmallRect writeRegion = new SmallRect((short)left, (short)top, (short)right, (short)bottom);

            if (!WinCon.WriteConsoleOutput(_handle, buff, bufferSize, bufferPos, writeRegion))
            {
                throw new IOException("Write error.", Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Reads characters from the screen buffer, starting at the given position.
        /// </summary>
        /// <param name="nChars">The number of characters to read.</param>
        /// <param name="x">Column position of the first character to read.</param>
        /// <param name="y">Row position of the first character to read.</param>
        /// <returns>A string containing the characters read from the screen buffer.</returns>
        public string ReadXY(int nChars, int x, int y)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            char[] buff      = new char[nChars];
            int    charsRead = 0;

            if (!WinCon.ReadConsoleOutputCharacter(_handle, buff, nChars,
                                                   new Coord((short)x, (short)y), ref charsRead))
            {
                throw new System.IO.IOException("Read error", Marshal.GetLastWin32Error());
            }
            return(new string(buff, 0, charsRead));
        }
Exemplo n.º 28
0
        private ConsoleScreenBufferInfo GetScreenBufferInfo()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            ConsoleScreenBufferInfo csbi = new ConsoleScreenBufferInfo();

            if (!WinCon.GetConsoleScreenBufferInfo(_handle, csbi))
            {
                int err = Marshal.GetLastWin32Error();
                Console.WriteLine("err = {0}", err);
                throw new IOException("Error getting screen buffer info", err);
            }
            return(csbi);
        }
Exemplo n.º 29
0
        private void ReadLineFromConsole()
        {
            // Magic number of 26608 was arrived at experimentally.
            // ReadConsole fails if you try to read more than that many characters.
            char[] buff        = new char[26608];
            int    charsToRead = buff.Length;
            int    charsRead   = 0;

            if (!WinCon.ReadConsole(handle, buff, charsToRead, ref charsRead, IntPtr.Zero))
            {
                int err = Marshal.GetLastWin32Error();
                throw new IOException("Error reading console input buffer", err);
            }
            sBuffer.Length = 0;
            sBuffer.Append(buff, 0, charsRead);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Retrieves all defined aliases for the specified executable.
        /// </summary>
        /// <param name="ExeName">The executable file whose aliases are to be retrieved.</param>
        /// <returns>Returns a NameValueCollection that contains the source and target
        /// (replacement) strings for all defined aliases.</returns>
        public static NameValueCollection GetAliases(string ExeName)
        {
            int length = GetAliasesLength(ExeName);
            NameValueCollection aliases = new NameValueCollection();

            if (length > 0)
            {
                char[] buff = new char[length];
                if (WinCon.GetConsoleAliases(buff, length, ExeName) == 0)
                {
                    throw new IOException("Unable to retrieve alias strings", Marshal.GetLastWin32Error());
                }
                // The returned buffer contains a series of nul-terminated strings
                // of the form source=target\0source=target\0
                // Parse the strings and add them to the aliases collection.
                int    startIndex = 0;
                string source     = "";
                string target     = "";
                bool   bSource    = true;
                for (int i = 0; i < length; i++)
                {
                    if (bSource)
                    {
                        // searching for source string
                        if (buff[i] == '=')
                        {
                            source     = new string(buff, startIndex, i - startIndex);
                            startIndex = i + 1;
                            bSource    = false;
                        }
                    }
                    else
                    {
                        // searching for target string
                        if (buff[i] == '\0')
                        {
                            target     = new string(buff, startIndex, i - startIndex);
                            startIndex = i + 1;
                            aliases.Add(source, target);
                            bSource = true;
                        }
                    }
                }
            }
            return(aliases);
        }