Skip to content

Instantly share code, notes, and snippets.

@joshschmelzle
Last active September 18, 2018 19:59
Show Gist options
  • Save joshschmelzle/610451c749dd14bb777a to your computer and use it in GitHub Desktop.
Save joshschmelzle/610451c749dd14bb777a to your computer and use it in GitHub Desktop.
Typewriter effect for C# console - https://gfycat.com/ObeseFancyAvians
using System;
using System.IO;
using System.Text;
using System.Threading;
namespace LazyWriter
{
class TypeWriter : System.IO.TextWriter
{
private TextWriter originalOut;
public TypeWriter()
{
originalOut = Console.Out;
}
public override void WriteLine(string message)
{
foreach (char c in message)
{
originalOut.Write(c);
if (!Console.KeyAvailable)
{
Thread.Sleep(25);
}
}
if (Console.KeyAvailable)
{
Console.ReadKey();
}
Animate();
if (Console.KeyAvailable)
{
Console.ReadKey();
}
originalOut.WriteLine();
}
private void Animate()
{
Console.CursorVisible = false;
for (int i = 0; i < 3; i++)
{
originalOut.Write(@"-");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
if (AnimationInterrupted()) break;
originalOut.Write(@"\");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
if (AnimationInterrupted()) break;
originalOut.Write(@"|");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
if (AnimationInterrupted()) break;
originalOut.Write(@"/");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
if (AnimationInterrupted()) break;
}
originalOut.Write(" ");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.CursorVisible = true;
}
private bool AnimationInterrupted()
{
if (!Console.KeyAvailable)
{
Thread.Sleep(50);
return false;
}
else
{
originalOut.Write(" ");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
return true;
}
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
}
// Sample usage
static void Main(string[] args)
{
TypeWriter typewriter = new TypeWriter();
Console.SetOut(typewriter);
Console.WriteLine("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...");
Console.WriteLine("There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain...");
Console.ReadKey();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment