/// <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"); } }
/// <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()); } }
/// <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)); }
/// <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()); } }
/// <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()); } }
/// <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); }
/// <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); }
/// <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(); }
// 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()); } }
/// <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()); } }
/// <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 (!WinCon.AttachConsole(processId)) { int err = Marshal.GetLastWin32Error(); throw new IOException(String.Format("Unable to attach console 0x{0,X}", processId), err); } SetupControlHandler(); }
/// <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); } }
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); }
/// <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); }
// 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; } }
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)); } }
public void Flush() { if (disposed) { throw new ObjectDisposedException(this.ToString()); } if (!WinCon.FlushConsoleInputBuffer(Handle)) { throw new System.IO.IOException("Error flushing buffer", Marshal.GetLastWin32Error()); } }
/// <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); }
/// <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"); } }
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); }
/// <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); }
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."); } }
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); }
/// <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()); } }
/// <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; }
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); }
public int ReadEvents(ConsoleInputEventInfo[] events) { if (disposed) { throw new ObjectDisposedException(this.ToString()); } int eventsRead = 0; if (!WinCon.ReadConsoleInput(Handle, events, events.Length, ref eventsRead)) { throw new System.IO.IOException("Unable to read events.", Marshal.GetLastWin32Error()); } return(eventsRead); }
/// <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()); } }
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); }
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); }