If the console moves, Pause. : Console « Development Class « C# / C Sharp






If the console moves, Pause.

        

using System;
using System.IO;

namespace CSharp.Util
{
  /// <summary>
  /// If the console moves, Pause.
  /// [Esc] throws an ApplicationException so you can exit.
  /// </summary>
  public class ConsolePause : IDisposable
  {
    int BeforeConsoleTop;
    int ExpectedLines = 0;
    bool Wait;
    public ConsolePause(bool wait)
    {
      Wait = wait;
      try
      {
        BeforeConsoleTop = Console.CursorTop;
      }
      catch (IOException)
      {
        // no console
      }
    }
    public void WriteLine(string s)
    {
      Console.WriteLine(s);
      ExpectedLines++;
    }
    public void warn(string s)
    {
      Console.ForegroundColor = ConsoleColor.Yellow;
      Console.WriteLine(s);
      Console.ForegroundColor = ConsoleColor.White;
      ExpectedLines++;
    }
    public void err(string s)
    {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine(s);
      Console.ForegroundColor = ConsoleColor.White;
    }

    public bool HasMessages
    {
      get
      {
        try
        {
          if (Console.CursorTop > BeforeConsoleTop + ExpectedLines)
            return true;
        }
        catch (IOException)
        {
        }
        return false;
      }
    }
    public void Dispose()
    {
      try
      {
        if (HasMessages)
        {
          err("Errors");
          if (Wait)
            if (Console.ReadKey().Key == ConsoleKey.Escape)
              throw new ApplicationException("done");
        }

        if (Console.BufferHeight > 1000)
          if (Console.CursorTop > Console.BufferHeight - 1000)
          {
            // Make more space so Console.CursorTop moves, instead of staying at the max.
            Console.Clear();
            Console.CursorTop = 0;
          }
      }
      catch(IOException)
      {
        // no console
      }
    }
  }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Echo some stats
2.Read a line of string and check its length
3.WriteLine and Write
4.Printing one line of text with multiple statements.
5.Printing multiple lines with a single statement.
6.Printing multiple lines of text with string formatting.
7.Displaying the sum of two numbers input from the keyboard.
8.Change console foreground color and background colorChange console foreground color and background color
9.Clear consoleClear console
10.Set console: title, window size, buffer height and width, cursor positionSet console: title, window size, buffer height and width, cursor position
11.CursorVisible ResetColor SetWindowSize BufferHeight BufferWidth CursorLeft CursorSize CursorTop
12.Use Red and Green from ConsoleColor
13.Beep
14.Beep(200, 300)
15.Use format specifiers with Console.WriteLine
16.Console Output Util