System.Console.ReadKey(bool)

Here are the examples of the csharp api System.Console.ReadKey(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

652 Examples 7

19 Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5

public static void Start()
        {
            Active = true;
            // loop
            Csecret = settings.Secret;
            while (client != null && Active)
            {
                // Get info
                FLInfo InitInfo = GetFLInfo();

                // Try to read any keys if available
                if (Console.In.Peek() != -1)
                {
                    switch (Console.ReadKey(true).Key)
                    {
                        case ConsoleKey.H:
                            Console.WriteLine("Commands: \n s: turn on secret mode \n q: Quit \n h: help \n Other settings can be changed in the settings.xml file");
                            break;
                        case ConsoleKey.S:
                            if (Csecret)
                            {
                                Csecret = false;
                                Console.WriteLine("\n Secret Mode turned off!");
                                rp.State = InitInfo.projectName;
                            }
                            else if (!Csecret)
                            {
                                Csecret = true;
                                Console.WriteLine("\n Secret Mode turned on!");
                                rp.State = settings.SecretMessage;
                            }

                            break;
                        case ConsoleKey.Q:
                            StopAndExit();
                            break;

                    }
                }


                if (client != null)
                    client.Invoke();


                //Skip update if nothing changes
                if (InitInfo.appName == rp.Details && InitInfo.projectName == rp.State && Csecret == Psecret)
                    continue;
                if (InitInfo.projectName == null && rp.State == settings.NoNameMessage && Csecret == Psecret)
                    continue;

                //Fill State and details
                if (InitInfo.projectName == null)
                {
                    rp.State = settings.NoNameMessage;
                    rp.Details = InitInfo.appName;
                }

                else
                {
                    rp.Details = InitInfo.appName;
                    rp.State = InitInfo.projectName;
                }
                if (Csecret)
                {
                    rp.State = settings.SecretMessage;
                }
                Psecret = Csecret;
                client.SetPresence(rp);
                Thread.Sleep(settings.RefeshInterval);


            }
        }

19 Source : Program.cs
with MIT License
from 13xforever

static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  gvas-converter path_to_save_file|path_to_json");
                return;
            }

            var ext = Path.GetExtension(args[0]).ToLower();
            if (ext == ".json")
            {
                Console.WriteLine("Not implemented atm");
            }
            else
            {
                Console.WriteLine("Parsing UE4 save file structure...");
                Gvas save;
                using (var stream = File.Open(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
                    save = UESerializer.Read(stream);

                Console.WriteLine("Converting to json...");
                var json = JsonConvert.SerializeObject(save, new JsonSerializerSettings{Formatting = Formatting.Indented});

                Console.WriteLine("Saving json...");
                using (var stream = File.Open(args[0] + ".json", FileMode.Create, FileAccess.Write, FileShare.Read))
                using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
                    writer.Write(json);
            }
            Console.WriteLine("Done.");
            Console.ReadKey(true);
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : Program.cs
with MIT License
from 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

private static void CommandInput()
        {
            Thread.Sleep(3000);
            Console.WriteLine(@"Available console commands: Q - quit (shutdown)
R - restart (shutdown and start), 
L - command to save players for shutdown (EverybodyLogoff)
S - save player statistics file");
            while (true)
            {
                Thread.Sleep(500);
                var key = Console.ReadKey(true);
                if (char.ToLower(key.KeyChar) == 'q') Manager.SaveAndQuit();
                if (char.ToLower(key.KeyChar) == 'r') Manager.SaveAndRestart();
                else if (char.ToLower(key.KeyChar) == 'l') Manager.EverybodyLogoff();
                else if (char.ToLower(key.KeyChar) == 's') Manager.SavePlayerStatisticsFile();
                else Console.WriteLine($"Unknow command: {char.ToUpper(key.KeyChar)}");
            }
        }

19 Source : Program.cs
with MIT License
from Abc-Arbitrage

public static void Main()
        {
            //Throughput();

            //LatencyMultiProducer(4, 4 * 25_000, 4 * 250_000, 64);
            //LatencyMultiProducer(8, 8 * 25_000, 8 * 250_000, 64);
            //LatencyMultiProducer(4, 4 * 25_000, 4 * 250_000, 1024);
            //LatencyMultiProducer(8, 8 * 25_000, 8 * 250_000, 1024);

            //EnumBenchmarksRunner.Run();
            //ThroughputToFileBench.Run();

            BenchmarkSwitcher.Fromreplacedembly(typeof(Program).replacedembly).Run();

            while (Console.KeyAvailable)
                Console.ReadKey(true);

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }

19 Source : ConsoleExtensions.cs
with Apache License 2.0
from acblog

public static string InputPreplacedword(string prompt = "")
        {
            Console.Write(prompt);
            StringBuilder sb = new StringBuilder();
            while (true)
            {
                var key = Console.ReadKey(true);
                if (key.Key is ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                sb.Append(key.KeyChar);
            }
            return sb.ToString();
        }

19 Source : Program.cs
with MIT License
from Accelerider

public static void ReadyToRun(IDownloader downloader)
        {
            WriteLine("Enter ant key to Start downloader: ");
            ReadKey(true);
            WriteLine("Try to Run... ");
            Subscribes(downloader.ToBindable());
            downloader.Run();
        }

19 Source : Terminal.cs
with MIT License
from actions

public string ReadSecret()
        {
            Trace.Info("READ SECRET");
            var chars = new List<char>();
            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey(intercept: true);
                if (key.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    if (chars.Count > 0)
                    {
                        chars.RemoveAt(chars.Count - 1);
                        Console.Write("\b \b");
                    }
                }
                else if (key.KeyChar > 0)
                {
                    chars.Add(key.KeyChar);
                    Console.Write("*");
                }
            }

            // Trace whether a value was entered.
            string val = new String(chars.ToArray());
            if (!string.IsNullOrEmpty(val))
            {
                HostContext.SecretMasker.AddValue(val);
            }

            Trace.Info($"Read value: '{val}'");
            return val;
        }

19 Source : Program.cs
with MIT License
from ADeltaX

static void Main(string[] args)
        {
            manager = new NowPlayingSessionManager();
            manager.SessionListChanged += SessionListChanged;
            SessionListChanged(null, null);

            char letter;
            do
            {
                var key = Console.ReadKey(true);
                letter = key.KeyChar.ToString().ToLower()[0];

                if (letter == 'p' || key.Key == ConsoleKey.Spacebar)
                    src.SendMediaPlaybackCommand(MediaPlaybackCommands.PlayPauseToggle); //MediaPlaybackCommands.Play or MediaPlaybackCommands.Pause

                if (letter == 'd' || key.Key == ConsoleKey.RightArrow)
                    src.SendMediaPlaybackCommand(MediaPlaybackCommands.Next);

                if (letter == 'a' || key.Key == ConsoleKey.LeftArrow)
                    src.SendMediaPlaybackCommand(MediaPlaybackCommands.Previous);

                if (letter == 'r' && session != null)
                    src.SendMediaPlaybackCommand(MediaPlaybackCommands.Rewind);

                if (letter == 'f' && session != null)
                    src.SendMediaPlaybackCommand(MediaPlaybackCommands.FastForward);

            } while (letter != 'q');
        }

19 Source : Program.cs
with MIT License
from alexanderdna

private static string readPreplacedphrase(System.Text.StringBuilder sb)
        {
            sb.Clear();
            while (true)
            {
                var key = Console.ReadKey(intercept: true);
                if (key.Modifiers != 0) continue;

                if (key.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                else if (key.Key == ConsoleKey.Escape)
                {
                    Console.WriteLine();
                    return null;
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    Console.WriteLine();
                    return string.Empty;
                }
                else if (key.KeyChar >= 20 && key.KeyChar < 256)
                {
                    Console.Write('*');
                    sb.Append(key.KeyChar);
                }
            }
            return sb.ToString();
        }

19 Source : Program.cs
with MIT License
from amerkoleci

static int Main(string[] args)
    {
        List<string> newArgs = new List<string>(args);
        newArgs.Insert(0, typeof(Program).replacedembly.Location);
        int returnCode = Xunit.ConsoleClient.Program.Main(newArgs.ToArray());
        Console.WriteLine("Tests finished. Press any key to exit.");
        if (!Console.IsInputRedirected)
        {
            Console.ReadKey(true);
        }
        return returnCode;
    }

19 Source : Program.cs
with MIT License
from amerkoleci

static void Main()
        {
            int userIndex = 0;

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    switch (Console.ReadKey(true).KeyChar)
                    {
                        case 'q':
                            return;

                        case char c when c >= '1' && c <= '4':
                            userIndex = c - '1';
                            break;
                    }
                }

                bool ok = XInput.GetState(userIndex, out State state);

                if (ok)
                {
                    XInput.SetVibration(userIndex, new Vibration
                    {
                        LeftMotorSpeed = (ushort)(state.Gamepad.LeftTrigger << 8),
                        RightMotorSpeed = (ushort)(state.Gamepad.RightTrigger << 8)
                    });
                }
                else
                {
                    state = new State();    // empty state variable if GetState failed
                }

                Console.SetCursorPosition(0, 0);

                ClearLine(); Console.WriteLine($"=========================================================================");
                ClearLine(); Console.WriteLine($"Press 1-4 to select gamepad, triggers control rumble, press 'q' to quit..");
                ClearLine(); Console.WriteLine($"=========================================================================");
                ClearLine(); Console.WriteLine($"Gamepad       : {userIndex + 1} {(ok ? "(ok)" : "(not ok)")}");
                ClearLine(); Console.WriteLine($"Buttons       : {state.Gamepad.Buttons}");
                ClearLine(); Console.WriteLine($"Left Thumb    : X = {state.Gamepad.LeftThumbX} Y = {state.Gamepad.LeftThumbY}");
                ClearLine(); Console.WriteLine($"Left Trigger  : {state.Gamepad.LeftTrigger}");
                ClearLine(); Console.WriteLine($"Right Thumb   : X = {state.Gamepad.RightThumbX} Y = {state.Gamepad.RightThumbY}");
                ClearLine(); Console.WriteLine($"Right Trigger : {state.Gamepad.RightTrigger}");

                Thread.Sleep(10);
            }
        }

19 Source : Program.cs
with MIT License
from Andrew-Hanlon

public static async Task MainAsync()
        {
            Console.WriteLine("AsyncEnumerator:");
            await Consumer();

            Console.WriteLine("\nAsyncSequence:");
            await Consumer2();

            Console.WriteLine("\nTaskLikeObservable:");
            await Consumer3();

            Console.WriteLine("\nCoopTask:");
            await Consumer4();

            Console.WriteLine("\nCoopTask2:");
            await Consumer5();

            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey(true);
        }

19 Source : Program.cs
with MIT License
from angelobreuer

private static async Task RunAsync()
        {
            using (var serviceProvider = ConfigureServices())
            {
                var bot = serviceProvider.GetRequiredService<ExampleBot>();
                var audio = serviceProvider.GetRequiredService<IAudioService>();
                var logger = serviceProvider.GetRequiredService<ILogger>() as EventLogger;
                logger.LogMessage += Log;

                await bot.StartAsync();
                await audio.InitializeAsync();

                logger.Log(bot, "Example Bot is running. Press [Q] to stop.");

                while (Console.ReadKey(true).Key != ConsoleKey.Q)
                {
                }

                await bot.StopAsync();
            }
        }

19 Source : Program.cs
with MIT License
from angelobreuer

private static async Task RunAsync()
        {
            using (var provider = BuildServiceProvider())
            {
                var client = provider.GetRequiredService<DiscordClient>();
                var audioService = provider.GetRequiredService<IAudioService>();
                var logger = provider.GetRequiredService<ILogger<Program>>();

                // connect to discord gateway and initialize node connection
                await client.ConnectAsync();
                await audioService.InitializeAsync();

                // join channel
                var track = await audioService.GetTrackAsync("<youtube search query>", SearchMode.YouTube);
                var player = await audioService.JoinAsync<LavalinkPlayer>(BotCredentials.GuildId, BotCredentials.VoiceChannelId);

                await player.PlayAsync(track);

                logger.LogInformation("Ready. Press [Q] to exit.");

                // wait until user presses [Q]
                while (Console.ReadKey(true).Key != ConsoleKey.Q)
                {
                }
            }
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

static async Task Main(string[] args)
        {
            /* Modbus RTU uses a COM port for communication. Therefore, to run
             * this sample, you need to make sure that there are real or virtual
             * COM ports available. The easiest way is to install one of the free
             * COM port bridges available in the internet. That way, the Modbus
             * server can connect to e.g. COM1 which is virtually linked to COM2,
             * where the client is connected to.
             *
             * When you only want to use the client and communicate to an external
             * Modbus server, simply remove all server related code parts in this
             * sample and connect to real COM port using only the client.
             */

            /* define COM ports */
            var serverPort = "COM1";
            var clientPort = "COM2";

            /* create logger */
            var loggerFactory = LoggerFactory.Create(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            });

            var serverLogger = loggerFactory.CreateLogger("Server");
            var clientLogger = loggerFactory.CreateLogger("Client");

            /* create Modbus RTU server */
            using var server = new ModbusRtuServer(unitIdentifier: 1)
            {
                // see 'RegistersChanged' event below
                EnableRaisingEvents = true
            };

            /* subscribe to the 'RegistersChanged' event (in case you need it) */
            server.RegistersChanged += (sender, registerAddresses) =>
            {
                // the variable 'registerAddresses' contains the unit ID and a list of modified register addresses
            };

            /* create Modbus RTU client */
            var client = new ModbusRtuClient();

            /* run Modbus RTU server */
            var cts = new CancellationTokenSource();

            var task_server = Task.Run(async () =>
            {
                server.Start(serverPort);
                serverLogger.LogInformation("Server started.");

                while (!cts.IsCancellationRequested)
                {
                    // lock is required to synchronize buffer access between this application and the Modbus client
                    lock (server.Lock)
                    {
                        DoServerWork(server);
                    }

                    // update server register content once per second
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }, cts.Token);

            /* run Modbus RTU client */
            var task_client = Task.Run(() =>
            {
                client.Connect(clientPort);

                try
                {
                    DoClientWork(client, clientLogger);
                }
                catch (Exception ex)
                {
                    clientLogger.LogError(ex.Message);
                }

                client.Close();

                Console.WriteLine("Tests finished. Press any key to continue.");
                Console.ReadKey(true);
            });

            // wait for client task to finish
            await task_client;

            // stop server
            cts.Cancel();
            await task_server;

            server.Stop();
            serverLogger.LogInformation("Server stopped.");
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

static async Task Main(string[] args)
        {
            /* create logger */
            var loggerFactory = LoggerFactory.Create(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            });

            var serverLogger = loggerFactory.CreateLogger("Server");
            var clientLogger = loggerFactory.CreateLogger("Client");

            /* create Modbus TCP server */
            using var server = new ModbusTcpServer(serverLogger)
            {
                // see 'RegistersChanged' event below
                EnableRaisingEvents = true
            };

            /* subscribe to the 'RegistersChanged' event (in case you need it) */
            server.RegistersChanged += (sender, registerAddresses) =>
            {
                // the variable 'registerAddresses' contains a list of modified register addresses
            };

            /* create Modbus TCP client */
            var client = new ModbusTcpClient();

            /* run Modbus TCP server */
            var cts = new CancellationTokenSource();

            var task_server = Task.Run(async () =>
            {
                server.Start();
                serverLogger.LogInformation("Server started.");

                while (!cts.IsCancellationRequested)
                {
                    // lock is required to synchronize buffer access between this application and one or more Modbus clients
                    lock (server.Lock)
                    {
                        DoServerWork(server);
                    }

                    // update server register content once per second
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }, cts.Token);

            /* run Modbus TCP client */
            var task_client = Task.Run(() =>
            {
                client.Connect();

                try
                {
                    DoClientWork(client, clientLogger);
                }
                catch (Exception ex)
                {
                    clientLogger.LogError(ex.Message);
                }

                client.Disconnect();

                Console.WriteLine("Tests finished. Press any key to continue.");
                Console.ReadKey(true);
            });

            // wait for client task to finish
            await task_client;

            // stop server
            cts.Cancel();
            await task_server;

            server.Stop();
            serverLogger.LogInformation("Server stopped.");
        }

19 Source : Program.cs
with Apache License 2.0
from AppMetrics

public static void Main(string[] args)
        {
            ConsoleKeyInfo keyInfo;

            do
            {
                BenchmarkSwitcher.Fromreplacedembly(typeof(BenchmarksreplacedemblyMarker).GetTypeInfo().replacedembly).Run(args);

                Console.WriteLine("Press ESC to quit, otherwise any key to continue...");

                keyInfo = Console.ReadKey(true);
            }
            while (keyInfo.Key != ConsoleKey.Escape);
        }

19 Source : Host.cs
with Apache License 2.0
from AppMetrics

private static async Task RunUntilEscAsync(TimeSpan delayBetweenRun, CancellationTokenSource cancellationTokenSource, Func<Task> action)
        {
            WriteLine("Press ESC to stop");

            while (true)
            {
                while (!KeyAvailable)
                {
                    await action();
                    Thread.Sleep(delayBetweenRun);
                }

                while (KeyAvailable)
                {
                    var key = ReadKey(false).Key;

                    if (key == ConsoleKey.Escape)
                    {
                        cancellationTokenSource.Cancel();
                        return;
                    }
                }
            }
        }

19 Source : Host.cs
with Apache License 2.0
from AppMetrics

private static async Task RunUntilEscAsync(TimeSpan delayBetweenRun, CancellationTokenSource cancellationTokenSource, Func<Task> action)
        {
            WriteLine("Press ESC to stop");

            while (true)
            {
                while (!KeyAvailable)
                {
                    await action();

                    Thread.Sleep(delayBetweenRun);
                }

                while (KeyAvailable)
                {
                    var key = ReadKey(false).Key;

                    if (key == ConsoleKey.Escape)
                    {
                        cancellationTokenSource.Cancel();
                        return;
                    }
                }
            }
        }

19 Source : Shell.cs
with MIT License
from Archomeda

public static Task StartRead()
        {
            cancellationTokenSource = new CancellationTokenSource();
            return Task.Run(async () =>
            {
                while (!stopRequested)
                {
                    // Implement our own reader since Console.ReadLine sucks in async and breaks our CTRL+C interrupt
                    SConsole.Write(">");
                    readingInput = true;
                    int pos = 0;
                    while (true)
                    {
                        var key = SConsole.ReadKey(true);
                        if (key.Modifiers.HasFlag(ConsoleModifiers.Control) && (key.Key == ConsoleKey.C || key.Key == ConsoleKey.Pause))
                        {
                            logger.LogMessage("{verb}Stopping...");
                            Program.Exit();
                            return;
                        }
                        else if (key.Key == ConsoleKey.Backspace)
                        {
                            if (pos > 0)
                            {
                                inputBuffer.Remove(pos - 1, 1);
                                lock (consoleLock)
                                    SConsole.Write("\b \b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.Delete)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                inputBuffer.Remove(pos, 1);
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + " " + new string('\b', inputBuffer.Length - pos + 1));
                            }
                        }
                        else if (key.Key == ConsoleKey.LeftArrow)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write("\b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.RightArrow)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer[pos]);
                                pos++;
                            }
                        }
                        else if (key.Key == ConsoleKey.Home)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write(new string('\b', pos));
                                pos = 0;
                            }
                        }
                        else if (key.Key == ConsoleKey.End)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos));
                                pos = inputBuffer.Length;
                            }
                        }
                        else if (key.Key == ConsoleKey.Enter)
                        {
                            lock (consoleLock)
                                SConsole.WriteLine();
                            break;
                        }
                        else if (key.KeyChar != 0)
                        {
                            inputBuffer.Insert(pos, key.KeyChar);
                            pos++;
                            lock (consoleLock)
                            {
                                SConsole.Write(key.KeyChar);
                                if (pos < inputBuffer.Length)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + new string('\b', inputBuffer.Length - pos));
                            }
                        }
                    }
                    readingInput = false;

                    var line = inputBuffer.ToString().Trim();
                    inputBuffer.Clear();
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    var verb = line.Split(new[] { ' ' }, 2)[0];
                    var command = Commands.FirstOrDefault(c => c.Verb == verb);

                    if (command != null)
                    {
                        try
                        {
                            await command.RunAsync(line.Substring(verb.Length).Trim(), cancellationTokenSource.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            // Fine...
                        }
                        catch (Exception ex)
                        {
                            logger.LogException(ex);
                        }
                    }
                    else
                        logger.LogCommandOutput("Unknown command, use {command}help{reset} to get the list of available commands.");
                    logger.LogCommandOutput("");
                }
            });
        }

19 Source : ConsoleWrapper.cs
with GNU Affero General Public License v3.0
from arklumpus

public static ConsoleKeyInfo ReadKey(bool intercept)
        {
            if (!Console.IsInputRedirected)
            {
                return Console.ReadKey(intercept);
            }
            else
            {
                int keyChar = Console.Read();
                ConsoleKey key = ConsoleKey.NoName;

                bool shift = false;
                bool ctrl = false;
                bool alt = false;

                if (keyChar < 0)
                {
                    keyChar = 'd';
                    key = ConsoleKey.D;
                    ctrl = true;
                }
                else if ((char)keyChar == '\n')
                {
                    key = ConsoleKey.Enter;
                }
                else if ((char)keyChar == '\t')
                {
                    key = ConsoleKey.Tab;
                }

                return new ConsoleKeyInfo((char)keyChar, key, shift, alt, ctrl);
            }
        }

19 Source : ConsoleMenu.cs
with MIT License
from arthurvaverko

private void StartConsoleDrawindLoopUntilInputIsMade()
        {
            int topOffset = Console.CursorTop;
            int bottomOffset = 0;
            ConsoleKeyInfo kb;
            Console.CursorVisible = false;


            while (!_ItemIsSelcted)
            {
                for (int i = 0; i < _menuItems.Length; i++)
                {
                    WriteConsoleItem(i, _SelectedItemIndex);
                }

                bottomOffset = Console.CursorTop;
                kb = Console.ReadKey(true);
                HandleKeyPress(kb.Key);

                //Reset the cursor to the top of the screen
                Console.SetCursorPosition(0, topOffset);
            }

            //set the cursor just after the menu so that the program can continue after the menu
            Console.SetCursorPosition(0, bottomOffset);
            Console.CursorVisible = true;
        }

19 Source : Exercicio9.18.cs
with MIT License
from atrigo

static void validaUtilizador(string[,] U)
        {
            char c;
            int tentativas = 0, tamanho = 10, nCarat, i;
            char[] p = new char[tamanho];
            string preplaced,user;
            do
            {
                Console.Clear();
                Console.Write("Introduza o username: ");
                user=Console.ReadLine();
                p.Initialize();
                preplaced = "";
                nCarat = 0;
                Console.Write("Introduza a preplacedword (letras maiúsculas/minúsculas e números - máx 10 caract): ");
                do
                {
                    c = Console.ReadKey(true).KeyChar;
                    if (c == 8)
                    {
                        if (nCarat > 0)
                        {
                            p[--nCarat] = (char)0;
                            Console.Write(c + " " + c);
                        }
                    }
                    else
                        if ((c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') && nCarat < tamanho)
                    {
                        p[nCarat++] = c;
                        Console.Write("*");
                    }
                } while (c != 13);
                tentativas++;
                i = 0;
                while (i < tamanho && p[i] != 0)
                {
                    preplaced += p[i];
                    i++;
                }
            } while ((user!=U[0,0] || preplaced != U[0,1]) && tentativas < 3);
            if (preplaced == U[0,1] && user==U[0,0])
                Console.WriteLine("\nValidação correta");
            else
                Console.WriteLine("\nExcedeu o número de tentativas");
        }

19 Source : Exercicio9.18.cs
with MIT License
from atrigo

static void registaUtilizador(string[,] U)
        {
            char c;
            int nCarat= 0, tamanho = 10;
            char[] p = new char[tamanho];
            Console.Write("Introduza o username: ");
            U[0,0] = Console.ReadLine();
            Console.Write("Introduza a preplacedword (letras maiúsculas/minúsculas e números - máx 10 caract): ");
            do
            {
                c = Console.ReadKey(true).KeyChar;
                if (c == 8)
                {
                    if (nCarat > 0)
                    {
                        p[--nCarat] = (char)0;
                        Console.Write(c + " " + c);
                    }
                }
                else
                    if ((c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') && nCarat < tamanho)
                {
                    p[nCarat++] = c;
                    Console.Write("*");
                }
            } while (c != 13);
            int i = 0;
            while (i < tamanho && p[i] != 0)
            {
                U[0,1]+= p[i];
                i++;
            }
            Console.WriteLine();
        }

19 Source : Exercicio10.6.cs
with MIT License
from atrigo

static void Main(string[] args)
        {
            char c;
            int tentativas = 0, tamanho = 10, nCarat, i,tenta=0;
            bool continua;
            do
            {
                try
                {
                    Console.Write("Quantas tentativas: ");
                    tenta = Convert.ToInt32(Console.ReadLine());
                    continua = false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    continua = true;
                }
            } while (continua);

            char[] p = new char[tamanho];
            string preplaced, pwd = "luar";
            do
            {
                Console.Clear();
                p.Initialize();
                preplaced = "";
                nCarat = 0;
                Console.Write("Introduza a preplacedword (letras maiúsculas/minúsculas e números - máx 10 caract): ");
                do
                {
                    c = Console.ReadKey(true).KeyChar;
                    if (c == 8)
                    {
                        if (nCarat > 0)
                        {
                            p[--nCarat] = (char)0;
                            Console.Write(c + " " + c);
                        }
                    }
                    else
                        if ((c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') && nCarat < tamanho)
                    {
                        p[nCarat++] = c;
                        Console.Write("*");
                    }
                } while (c != 13);
                tentativas++;
                i = 0;
                while (i < tamanho && p[i] != 0)
                {
                    preplaced += p[i];
                    i++;
                }
            } while (preplaced != pwd && tentativas < tenta);
            if (preplaced == pwd)
                Console.WriteLine("\nPreplacedword correta");
            else
                Console.WriteLine("\nExcedeu o número de tentativas");
        }

19 Source : ExampleDebug.cs
with MIT License
from audinowho

public static ConsoleKey PrintListRoomHalls(IGenContext map, string msg, bool printDebug, bool printViewer)
        {
            if (!(map is IFloorPlanGenContext context))
                return ConsoleKey.Enter;

            var str = new StringBuilder();
            FloorPlan plan = context.RoomPlan;
            if (plan == null)
                return ConsoleKey.Enter;

            for (int yy = 0; yy < plan.DrawRect.Bottom; yy++)
            {
                for (int xx = 0; xx < plan.DrawRect.Right; xx++)
                {
                    str.Append(' ');
                }
            }

            for (int ii = 0; ii < plan.RoomCount; ii++)
            {
                char chosenChar = (char)('A' + (ii % 26));
                IRoomGen gen = plan.GetRoom(ii);
                for (int xx = gen.Draw.Left; xx < gen.Draw.Right; xx++)
                {
                    for (int yy = gen.Draw.Top; yy < gen.Draw.Bottom; yy++)
                    {
                        int index = (yy * plan.DrawRect.Right) + xx;

                        if (str[index] == ' ')
                            str[index] = chosenChar;
                        else
                            str[index] = '!';
                    }
                }
            }

            for (int ii = 0; ii < plan.HallCount; ii++)
            {
                char chosenChar = (char)('a' + (ii % 26));

                IRoomGen gen = plan.GetHall(ii);

                for (int xx = gen.Draw.Left; xx < gen.Draw.Right; xx++)
                {
                    for (int yy = gen.Draw.Top; yy < gen.Draw.Bottom; yy++)
                    {
                        int index = (yy * plan.DrawRect.Right) + xx;

                        if (str[index] == ' ')
                            str[index] = chosenChar;
                        else if ((str[index] >= 'a' && str[index] <= 'z') || str[index] == '#')
                            str[index] = '+';
                        else
                            str[index] = '!';
                    }
                }
            }

            for (int yy = plan.DrawRect.Bottom - 1; yy > 0; yy--)
                str.Insert(plan.DrawRect.Right * yy, '\n');

            string newStr = str.ToString();
            if (listDebugString[currentDepth].MapString == newStr)
                return ConsoleKey.Enter;

            listDebugString[currentDepth].MapString = newStr;

            if (printDebug)
            {
                Debug.WriteLine(msg);
                Debug.Print(newStr);
            }

            if (printViewer)
            {
                SteppingIn = false;
                Console.Clear();
                Console.WriteLine(msg);
                Loc start = new Loc(Console.CursorLeft, Console.CursorTop);
                Console.Write(newStr);
                Loc end = new Loc(Console.CursorLeft, Console.CursorTop + 1);
                Console.SetCursorPosition(start.X, start.Y);
                int prevFarthestPrint = end.Y;

                while (true)
                {
                    int farthestPrint = end.Y;
                    Loc mapLoc = new Loc(Console.CursorLeft, Console.CursorTop) - start;
                    RewriteLine(farthestPrint, $"X:{mapLoc.X:D3}  Y:{mapLoc.Y:D3}");
                    farthestPrint++;

                    for (int ii = 0; ii < plan.RoomCount; ii++)
                    {
                        FloorRoomPlan roomPlan = plan.GetRoomPlan(ii);
                        if (roomPlan.RoomGen.Draw.Contains(mapLoc))
                        {
                            // stats
                            string roomString = $"Room #{ii}: {roomPlan.RoomGen.Draw.X}x{roomPlan.RoomGen.Draw.Y} {roomPlan.RoomGen}";
                            RewriteLine(farthestPrint, roomString);
                            farthestPrint++;
                            string componentString = string.Format("Components: {0}", string.Join(", ", roomPlan.Components));
                            RewriteLine(farthestPrint, componentString);
                            farthestPrint++;

                            // borders
                            var lineString = new StringBuilder(" ");
                            for (int xx = 0; xx < roomPlan.RoomGen.Draw.Width; xx++)
                                lineString.Append(roomPlan.RoomGen.GetFulfillableBorder(Dir4.Up, xx) ? "^" : " ");
                            RewriteLine(farthestPrint, lineString.ToString());
                            farthestPrint++;
                            for (int yy = 0; yy < roomPlan.RoomGen.Draw.Height; yy++)
                            {
                                lineString = new StringBuilder(roomPlan.RoomGen.GetFulfillableBorder(Dir4.Left, yy) ? "<" : " ");
                                for (int xx = 0; xx < roomPlan.RoomGen.Draw.Width; xx++)
                                    lineString.Append("#");
                                lineString.Append(roomPlan.RoomGen.GetFulfillableBorder(Dir4.Right, yy) ? ">" : " ");
                                RewriteLine(farthestPrint, lineString.ToString());
                                farthestPrint++;
                            }

                            lineString = new StringBuilder(" ");
                            for (int xx = 0; xx < roomPlan.RoomGen.Draw.Width; xx++)
                                lineString.Append(roomPlan.RoomGen.GetFulfillableBorder(Dir4.Down, xx) ? "V" : " ");
                            RewriteLine(farthestPrint, lineString.ToString());
                            farthestPrint++;
                        }
                    }

                    for (int ii = 0; ii < plan.HallCount; ii++)
                    {
                        FloorHallPlan hallPlan = plan.GetHallPlan(ii);
                        if (hallPlan.RoomGen.Draw.Contains(mapLoc))
                        {
                            string roomString = $"Hall #{ii}: {hallPlan.RoomGen.Draw.X}x{hallPlan.RoomGen.Draw.Y} {hallPlan.RoomGen}";
                            RewriteLine(farthestPrint, roomString);
                            farthestPrint++;
                            string componentString = string.Format("Components: {0}", string.Join(", ", hallPlan.Components));
                            RewriteLine(farthestPrint, componentString);
                            farthestPrint++;
                        }
                    }

                    for (int ii = farthestPrint; ii < prevFarthestPrint; ii++)
                        ClearLine(ii);
                    prevFarthestPrint = farthestPrint;
                    Console.SetCursorPosition(start.X + mapLoc.X, start.Y + mapLoc.Y);

                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.UpArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Max(start.Y, Console.CursorTop - 1));
                    else if (key.Key == ConsoleKey.DownArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Min(Console.CursorTop + 1, end.Y - 1));
                    else if (key.Key == ConsoleKey.LeftArrow)
                        Console.SetCursorPosition(Math.Max(start.X, Console.CursorLeft - 1), Console.CursorTop);
                    else if (key.Key == ConsoleKey.RightArrow)
                        Console.SetCursorPosition(Math.Min(Console.CursorLeft + 1, end.X - 1), Console.CursorTop);
                    else
                        return key.Key;
                }
            }
            else
            {
                return ConsoleKey.Enter;
            }
        }

19 Source : Program.cs
with MIT License
from audinowho

public static void Main()
        {
#if DEBUG
            GenContextDebug.OnInit += ExampleDebug.Init;
            GenContextDebug.OnStep += ExampleDebug.OnStep;
            GenContextDebug.OnStepIn += ExampleDebug.StepIn;
            GenContextDebug.OnStepOut += ExampleDebug.StepOut;
#endif
            ConsoleKey lastKey = ConsoleKey.Enter;
            bool wasNonAction = false;
            bool done = false;
            while (!done)
            {
                ConsoleKey key = ConsoleKey.Enter;
                if (!wasNonAction)
                {
                    if (lastKey != ConsoleKey.Enter)
                    {
                        Console.WriteLine("Press a key 1-8 | F4=Debug");
                        Console.WriteLine("While debugging: F5=Step-In | F6=Step-Out | ESC=Exit Debug");
                    }
                    else
                    {
                        Console.WriteLine("Press a key 1-8:");
                    }
                }

                key = Console.ReadKey(true).Key;

                if (key == ConsoleKey.F2)
                {
                    while (true)
                    {
                        Console.Clear();
                        Console.WriteLine(">Bulk Gen");
                        Console.WriteLine("Specify amount to generate");
                        int amt = GetInt(false);
                        if (amt > -1)
                        {
                            Console.WriteLine("Stress Test WIP.");
                            ConsoleKeyInfo afterKey = Console.ReadKey();
                            if (afterKey.Key == ConsoleKey.Escape)
                                break;
                        }
                        else if (amt == -1)
                        {
                            break;
                        }
                    }
                }
                else if (key == ConsoleKey.F4)
                {
                    ExampleDebug.SteppingIn = true;
                    key = lastKey;
                }

                bool keepKey = true;
                wasNonAction = false;
                switch (key)
                {
                    case ConsoleKey.D1:
                        Ex1_Tiles.Example1.Run();
                        break;
                    case ConsoleKey.D2:
                        Ex2_Rooms.Example2.Run();
                        break;
                    case ConsoleKey.D3:
                        Ex3_Grid.Example3.Run();
                        break;
                    case ConsoleKey.D4:
                        Ex4_Stairs.Example4.Run();
                        break;
                    case ConsoleKey.D5:
                        Ex5_Terrain.Example5.Run();
                        break;
                    case ConsoleKey.D6:
                        Ex6_Items.Example6.Run();
                        break;
                    case ConsoleKey.D7:
                        Ex7_Special.Example7.Run();
                        break;
                    case ConsoleKey.D8:
                        Ex8_Integration.Example8.Run();
                        break;
                    case ConsoleKey.Escape:
                        done = true;
                        break;
                    default:
                        keepKey = false;
                        wasNonAction = true;
                        break;
                }

                if (keepKey)
                    lastKey = key;

                ExampleDebug.SteppingIn = false;
            }

            Console.WriteLine("Bye.");
            Console.ReadKey();
        }

19 Source : Program.cs
with MIT License
from audinowho

public static int GetInt(bool includeAmt)
        {
            int result = 0;

            ConsoleKeyInfo key = Console.ReadKey(true);
            while (key.Key != ConsoleKey.Enter)
            {
                if (key.Key == ConsoleKey.Escape)
                    return -1;
                if (includeAmt && key.Key == ConsoleKey.F2)
                    return -2;

                if (key.KeyChar >= '0' && key.KeyChar <= '9')
                {
                    Console.Write(key.KeyChar);
                    result = (result * 10) + key.KeyChar - '0';
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    Console.Write("\b \b");
                    result /= 10;
                }

                key = Console.ReadKey(true);
            }

            Console.WriteLine();
            return result;
        }

19 Source : ExampleDebug.cs
with MIT License
from audinowho

public static ConsoleKey PrintTiles(IGenContext map, string msg, bool printDebug, bool printViewer)
        {
            if (!(map is ITiledGenContext context))
                return ConsoleKey.Enter;
            if (!context.TilesInitialized)
                return ConsoleKey.Enter;

            var str = new StringBuilder();

            for (int yy = 0; yy < context.Height; yy++)
            {
                if (yy > 0)
                    str.Append('\n');
                for (int xx = 0; xx < context.Width; xx++)
                {
                    if (context.GetTile(new Loc(xx, yy)).TileEquivalent(context.RoomTerrain))
                    {
                        str.Append('.');
                    }
                    else if (context.GetTile(new Loc(xx, yy)).TileEquivalent(context.WallTerrain))
                    {
                        str.Append('#');
                    }
                    else
                    {
                        if (context.TileBlocked(new Loc(xx, yy)))
                            str.Append('+');
                        else
                            str.Append('_');
                    }
                }
            }

            string newStr = str.ToString();
            if (tileDebugString[currentDepth].MapString == newStr)
                return ConsoleKey.Enter;

            tileDebugString[currentDepth].MapString = newStr;

            if (printDebug)
            {
                Debug.WriteLine(msg);
                Debug.Print(newStr);
            }

            if (printViewer)
            {
                // TODO: print with highlighting (use the bounds variable)
                // TODO: print with color
                SteppingIn = false;
                Console.Clear();
                Console.WriteLine(msg);
                Loc start = new Loc(Console.CursorLeft, Console.CursorTop);
                Console.Write(newStr);
                Loc end = new Loc(Console.CursorLeft, Console.CursorTop + 1);
                Console.SetCursorPosition(start.X, start.Y);
                int prevFarthestPrint = end.Y;

                while (true)
                {
                    int farthestPrint = end.Y;
                    Loc mapLoc = new Loc(Console.CursorLeft, Console.CursorTop) - start;
                    RewriteLine(farthestPrint, $"X:{mapLoc.X:D3}  Y:{mapLoc.Y:D3}");
                    farthestPrint++;
                    ITile tile = context.GetTile(mapLoc);
                    RewriteLine(farthestPrint, $"Tile: {tile}");
                    farthestPrint++;

                    for (int ii = farthestPrint; ii < prevFarthestPrint; ii++)
                        ClearLine(ii);
                    prevFarthestPrint = farthestPrint;
                    Console.SetCursorPosition(start.X + mapLoc.X, start.Y + mapLoc.Y);

                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.UpArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Max(start.Y, Console.CursorTop - 1));
                    else if (key.Key == ConsoleKey.DownArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Min(Console.CursorTop + 1, end.Y - 1));
                    else if (key.Key == ConsoleKey.LeftArrow)
                        Console.SetCursorPosition(Math.Max(start.X, Console.CursorLeft - 1), Console.CursorTop);
                    else if (key.Key == ConsoleKey.RightArrow)
                        Console.SetCursorPosition(Math.Min(Console.CursorLeft + 1, end.X - 1), Console.CursorTop);
                    else
                        return key.Key;
                }
            }
            else
            {
                return ConsoleKey.Enter;
            }
        }

19 Source : ExampleDebug.cs
with MIT License
from audinowho

public static ConsoleKey PrintGridRoomHalls(IGenContext map, string msg, bool printDebug, bool printViewer)
        {
            if (!(map is IRoomGridGenContext context))
                return ConsoleKey.Enter;

            var str = new StringBuilder();
            GridPlan plan = context.GridPlan;
            if (plan == null)
                return ConsoleKey.Enter;

            for (int yy = 0; yy < plan.GridHeight; yy++)
            {
                if (yy > 0)
                    str.Append('\n');

                for (int xx = 0; xx < plan.GridWidth; xx++)
                {
                    int roomIndex = plan.GetRoomIndex(new Loc(xx, yy));
                    if (roomIndex == -1)
                        str.Append('0');
                    else // if (roomIndex < 26)
                        str.Append((char)('A' + (roomIndex % 26)));
                    /* else
                           str.Append('@');
                    */

                    if (xx < plan.GridWidth - 1)
                    {
                        if (plan.GetHall(new LocRay4(xx, yy, Dir4.Right)) != null)
                            str.Append('#');
                        else
                            str.Append('.');
                    }
                }

                if (yy < plan.GridHeight - 1)
                {
                    str.Append('\n');
                    for (int xx = 0; xx < plan.GridWidth; xx++)
                    {
                        if (plan.GetHall(new LocRay4(xx, yy, Dir4.Down)) != null)
                            str.Append('#');
                        else
                            str.Append('.');

                        if (xx < plan.GridWidth - 1)
                        {
                            str.Append(' ');
                        }
                    }
                }
            }

            string newStr = str.ToString();
            if (gridDebugString[currentDepth].MapString == newStr)
                return ConsoleKey.Enter;

            gridDebugString[currentDepth].MapString = newStr;

            if (printDebug)
            {
                Debug.WriteLine(msg);
                Debug.Print(newStr);
            }

            if (printViewer)
            {
                SteppingIn = false;
                Console.Clear();
                Console.WriteLine(msg);
                Loc start = new Loc(Console.CursorLeft, Console.CursorTop);
                Console.Write(newStr);
                Loc end = new Loc(Console.CursorLeft, Console.CursorTop + 1);
                Console.SetCursorPosition(start.X, start.Y);
                int prevFarthestPrint = end.Y;

                while (true)
                {
                    int farthestPrint = end.Y;
                    Loc gridLoc = new Loc(Console.CursorLeft, Console.CursorTop) - start;
                    Loc mapLoc = gridLoc / 2;
                    RewriteLine(farthestPrint, $"X:{gridLoc.X / 2f:0.0}  Y:{gridLoc.Y / 2f:0.0}");
                    farthestPrint++;

                    bool alignX = gridLoc.X % 2 == 0;
                    bool alignY = gridLoc.Y % 2 == 0;

                    if (alignX && alignY)
                    {
                        int index = plan.GetRoomIndex(mapLoc);
                        GridRoomPlan roomPlan = plan.GetRoomPlan(mapLoc);
                        if (roomPlan != null)
                        {
                            string roomString = $"Room #{index}: {roomPlan.RoomGen}";
                            if (roomPlan.PreferHall)
                                roomString += " [Hall]";
                            RewriteLine(farthestPrint, roomString);
                            farthestPrint++;
                            string componentString = string.Format("Components: {0}", string.Join(", ", roomPlan.Components));
                            RewriteLine(farthestPrint, componentString);
                            farthestPrint++;
                        }
                    }
                    else if (alignX)
                    {
                        GridHallPlan hall = plan.GetHall(new LocRay4(mapLoc, Dir4.Down));
                        if (hall != null)
                        {
                            RewriteLine(farthestPrint, "Hall: " + hall.RoomGen);
                            farthestPrint++;
                            string componentString = string.Format("Components: {0}", string.Join(", ", hall.Components));
                            RewriteLine(farthestPrint, componentString);
                            farthestPrint++;
                        }
                    }
                    else if (alignY)
                    {
                        GridHallPlan hall = plan.GetHall(new LocRay4(mapLoc, Dir4.Right));
                        if (hall != null)
                        {
                            RewriteLine(farthestPrint, "Hall: " + hall.RoomGen);
                            farthestPrint++;
                        }
                    }

                    for (int ii = farthestPrint; ii < prevFarthestPrint; ii++)
                        ClearLine(ii);
                    prevFarthestPrint = farthestPrint;
                    Console.SetCursorPosition(start.X + gridLoc.X, start.Y + gridLoc.Y);

                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.UpArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Max(start.Y, Console.CursorTop - 1));
                    else if (key.Key == ConsoleKey.DownArrow)
                        Console.SetCursorPosition(Console.CursorLeft, Math.Min(Console.CursorTop + 1, end.Y - 1));
                    else if (key.Key == ConsoleKey.LeftArrow)
                        Console.SetCursorPosition(Math.Max(start.X, Console.CursorLeft - 1), Console.CursorTop);
                    else if (key.Key == ConsoleKey.RightArrow)
                        Console.SetCursorPosition(Math.Min(Console.CursorLeft + 1, end.X - 1), Console.CursorTop);
                    else
                        return key.Key;
                }
            }
            else
            {
                return ConsoleKey.Enter;
            }
        }

19 Source : Editor.cs
with BSD 3-Clause "New" or "Revised" License
from aura-systems

internal void Start(string filename, string currentdirectory)
        {
            if (File.Exists(currentdirectory + filename))
            {
                Console.Clear();
                drawTopBar();
                Console.SetCursorPosition(0, 1);
                ConsoleKeyInfo c; cleanArray(line);

                List<string> text = new List<string>();
                text.Add(File.ReadAllText(currentdirectory + filename));

                string file = "";

                foreach (string value in text)
                {
                    file = file + value;
                }

                Console.Write(file);

                while ((c = Console.ReadKey(true)) != null)
                {
                    drawTopBar();
                    char ch = c.KeyChar;
                    if (c.Key == ConsoleKey.Escape)
                        break;

                    else if (c.Key == ConsoleKey.F1)
                    {
                        Console.Clear();
                        Console.BackgroundColor = ConsoleColor.Gray;
                        Console.ForegroundColor = ConsoleColor.Black;
                        Text.Display("liquideditor", prgm_version);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.BackgroundColor = ConsoleColor.Black;

                        lines.Add(new string(line).TrimEnd());

                        final = lines.ToArray();
                        string foo = concatString(final);
                        File.Create(currentdirectory + filename);
                        File.WriteAllText(currentdirectory + filename, file + foo);
                        Console.ForegroundColor = ConsoleColor.Green;
                        Text.Display("saved", filename, currentdirectory);
                        Console.ForegroundColor = ConsoleColor.White;

                        Console.ReadKey();
                        break;
                    }

                    else if (c.Key == ConsoleKey.F2)
                    {
                        filepath(Kernel.current_directory);
                        break;
                    }

                    switch (c.Key)
                    {
                        case ConsoleKey.Home: break;
                        case ConsoleKey.PageUp: break;
                        case ConsoleKey.PageDown: break;
                        case ConsoleKey.End: break;
                        case ConsoleKey.UpArrow:
                            if (Console.CursorTop > 1)
                            {
                                Console.CursorTop = Console.CursorTop - 1;
                            }
                            break;
                        case ConsoleKey.DownArrow:
                            if (Console.CursorTop < 24)
                            {
                                Console.CursorTop = Console.CursorTop + 1;
                            }
                            break;
                        case ConsoleKey.LeftArrow: if (pointer > 0) { pointer--; Console.CursorLeft--; } break;
                        case ConsoleKey.RightArrow: if (pointer < 80) { pointer++; Console.CursorLeft++; if (line[pointer] == 0) line[pointer] = ' '; } break;
                        case ConsoleKey.Backspace: deleteChar(); break;
                        case ConsoleKey.Delete: deleteChar(); break;
                        case ConsoleKey.Enter:
                            lines.Add(new string(line).TrimEnd()); cleanArray(line); Console.CursorLeft = 0; Console.CursorTop++; pointer = 0;
                            break;
                        default: line[pointer] = ch; pointer++; Console.Write(ch); break;
                    }
                }
                Console.Clear();

            }
            else
            {
            Console.Clear();
            drawTopBar();
            Console.SetCursorPosition(0, 1);
            ConsoleKeyInfo c; cleanArray(line);
            while ((c = Console.ReadKey(true)) != null)
            {
                drawTopBar();
                char ch = c.KeyChar;
                if (c.Key == ConsoleKey.Escape)
                    break;
                else if (c.Key == ConsoleKey.F1)
                {
                    Console.Clear();
                    Console.BackgroundColor = ConsoleColor.Gray;
                    Console.ForegroundColor = ConsoleColor.Black;
                    Text.Display("liquideditor", prgm_version);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.BackgroundColor = ConsoleColor.Black;

                    lines.Add(new string(line).TrimEnd());

                    final = lines.ToArray();
                    string foo = concatString(final);
                    File.Create(currentdirectory + filename);
                    File.WriteAllText(currentdirectory + filename, foo); 
                    Console.ForegroundColor = ConsoleColor.Green;
                    Text.Display("saved", filename, currentdirectory);
                    Console.ForegroundColor = ConsoleColor.White;

                    Console.ReadKey();
                    break;
                }
                else if (c.Key == ConsoleKey.F2)
                {
                    filepath(Kernel.current_directory);
                    break;
                }
                    switch (c.Key)
                {
                    case ConsoleKey.Home: break;
                    case ConsoleKey.PageUp: break;
                    case ConsoleKey.PageDown: break;
                    case ConsoleKey.End: break;
                    case ConsoleKey.UpArrow:
                        if (Console.CursorTop > 1)
                        {
                            Console.CursorTop = Console.CursorTop - 1;
                        }
                        break;
                    case ConsoleKey.DownArrow:
                        if (Console.CursorTop < 23)
                        {
                            Console.CursorTop = Console.CursorTop + 1;
                        }
                        break;
                    case ConsoleKey.LeftArrow: if (pointer > 0) { pointer--; Console.CursorLeft--; } break;
                    case ConsoleKey.RightArrow: if (pointer < 80) { pointer++; Console.CursorLeft++; if (line[pointer] == 0) line[pointer] = ' '; } break;
                    case ConsoleKey.Backspace: deleteChar(); break;
                    case ConsoleKey.Delete: deleteChar(); break;
                    case ConsoleKey.Enter:
                        lines.Add(new string(line).TrimEnd()); cleanArray(line); Console.CursorLeft = 0; Console.CursorTop++; pointer = 0;
                        break;
                    default: line[pointer] = ch; pointer++; Console.Write(ch); break;
                }
            }
            Console.Clear();
            }
        }

19 Source : Snake.cs
with BSD 3-Clause "New" or "Revised" License
from aura-systems

public void Run()
        {
            Console.Clear();
            printLogo();
            Console.Write("Welcome to Snake, write snake to start the game: ");
            switch (Console.ReadLine())
            {
                case "snake":
                    configSnake();
                    ConsoleKey x;
                    while (true)
                    {
                        while (gameover())
                        {
                            printGame();
                            Boolean endGame = false;
                            switch (Console.ReadKey(true).Key)
                            {
                                case ConsoleKey.R:
                                    configSnake();
                                    break;
                                case ConsoleKey.Escape:
                                    endGame = true;
                                    break;
                            }

                            if (endGame)
                            {
                                break;
                            }
                        }
                        while (!Console.KeyAvailable && !gameover())
                        {

                            updateDirections();

                            updatePosotion();

                            checkIfTouchFood();

                            Console.Clear();
                            changeArray();
                            printGame();
                            delay(10000000);
                        }

                        x = Console.ReadKey(true).Key;

                        if (x == ConsoleKey.LeftArrow)
                        {
                            if (snake[0][1] != 3)
                            {
                                commands.Add(new int[2] { 1, 0 });
                            }
                        }
                        else if (x == ConsoleKey.UpArrow)
                        {
                            if (snake[0][1] != 2)
                            {
                                commands.Add(new int[2] { 4, 0 });
                            }
                        }
                        else if (x == ConsoleKey.RightArrow)
                        {
                            if (snake[0][1] != 1)
                            {
                                commands.Add(new int[2] { 3, 0 });
                            }
                        }
                        else if (x == ConsoleKey.DownArrow)
                        {
                            if (snake[0][1] != 4)
                            {
                                commands.Add(new int[2] { 2, 0 });
                            }
                        }
                        else if (x == ConsoleKey.Escape)
                        {
                            Console.Clear();
                            break;
                        }
                        else if (x == ConsoleKey.R)
                        {
                            configSnake();
                        }
                    }
                    break;
                default:
                    Console.WriteLine("Wrong option.");
                    Run();
                    break;
            }
        }

19 Source : Menu.cs
with BSD 3-Clause "New" or "Revised" License
from aura-systems

public static int GenericMenu(string[] items, Action method, int x, int y)
        {
            int currenreplacedem = 0, c;
            var key = new ConsoleKeyInfo();

            method();

            int counter = y + 3;
            for (c = 0; c < items.Length; c++)
            {
                counter = counter + 1;
                if (currenreplacedem == c)
                {
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.SetCursorPosition(x + 2, counter);
                    Console.Write("* ");
                    Console.WriteLine(items[c]);
                    Console.SetCursorPosition(x_lang, y_lang);
                    Console.BackgroundColor = ConsoleColor.Black;
                }
                else
                {
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.SetCursorPosition(x + 2, counter);
                    Console.WriteLine("  " + items[c]);
                    Console.SetCursorPosition(x_lang, y_lang);
                    Console.BackgroundColor = ConsoleColor.Black;
                }
            }

            while (key.Key != ConsoleKey.Enter)
            {
                key = Console.ReadKey(true);

                if (key.Key == ConsoleKey.DownArrow)
                {
                    currenreplacedem++;
                    if (currenreplacedem > items.Length - 1) currenreplacedem = 0;

                    method();

                    counter = y + 3;
                    for (c = 0; c < items.Length; c++)
                    {
                        counter = counter + 1;
                        if (currenreplacedem == c)
                        {
                            Console.BackgroundColor = ConsoleColor.DarkBlue;
                            Console.SetCursorPosition(x + 2, counter);
                            Console.WriteLine("*");
                            Console.SetCursorPosition(x_lang, y_lang);
                            Console.BackgroundColor = ConsoleColor.Black;
                        }
                        else
                        {
                            Console.BackgroundColor = ConsoleColor.DarkBlue;
                            Console.SetCursorPosition(x + 2, counter);
                            Console.WriteLine(" ");
                            Console.SetCursorPosition(x_lang, y_lang);
                            Console.BackgroundColor = ConsoleColor.Black;
                        }
                    }
                }
                else if (key.Key == ConsoleKey.UpArrow)
                {
                    currenreplacedem--;
                    if (currenreplacedem < 0) currenreplacedem = items.Length - 1;

                    method();

                    counter = y + 3;
                    for (c = 0; c < items.Length; c++)
                    {
                        counter = counter + 1;
                        if (currenreplacedem == c)
                        {
                            Console.BackgroundColor = ConsoleColor.DarkBlue;
                            Console.SetCursorPosition(x + 2, counter);
                            Console.Write("* ");
                            Console.WriteLine(items[c]);
                            Console.SetCursorPosition(x_lang, y_lang);
                            Console.BackgroundColor = ConsoleColor.Black;
                        }
                        else
                        {
                            Console.BackgroundColor = ConsoleColor.DarkBlue;
                            Console.SetCursorPosition(x + 2, counter);
                            Console.WriteLine("  " + items[c]);
                            Console.SetCursorPosition(x_lang, y_lang);
                            Console.BackgroundColor = ConsoleColor.Black;
                        }
                    }
                }
            }

            return currenreplacedem;
        }

19 Source : App.xaml.cs
with MIT License
from AvaloniaCommunity

static void SilenceConsole()
        {
            new Thread(() =>
            {
                Console.CursorVisible = false;
                while (true)
                    Console.ReadKey(true);
            })
            { IsBackground = true }.Start();
        }

19 Source : Utilities.cs
with Apache License 2.0
from aws

public static string ReadSecretFromConsole()
        {
            var code = new StringBuilder();
            while (true)
            {
                ConsoleKeyInfo i = Console.ReadKey(true);
                if (i.Key == ConsoleKey.Enter)
                {
                    break;
                }
                else if (i.Key == ConsoleKey.Backspace)
                {
                    if (code.Length > 0)
                    {
                        code.Remove(code.Length - 1, 1);
                        Console.Write("\b \b");
                    }
                }
                // i.Key > 31: Skip the initial ascii control characters like ESC and tab. The space character is 32.
                // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
                else if ((int)i.Key > 31 && i.KeyChar != '\u0000') 
                {
                    code.Append(i.KeyChar);
                    Console.Write("*");
                }
            }
            return code.ToString().Trim();
        }

19 Source : CredentialsArguments.cs
with Apache License 2.0
from aws

private static String ReadMFACode()
        {
            Console.Write("Enter MFA code:");

            String mfaCode = "";
            while (true)
            {
                ConsoleKeyInfo info = Console.ReadKey(true);
                if (info.Key == ConsoleKey.Backspace)
                {
                    if (mfaCode.Length > 0)
                    {
                        // remove the character from the string
                        mfaCode = mfaCode.Remove(mfaCode.Length - 1);

                        // remove the * from the console
                        var position = Console.CursorLeft - 1;
                        Console.SetCursorPosition(position, Console.CursorTop);
                        Console.Write(" ");
                        Console.SetCursorPosition(position, Console.CursorTop);
                    }
                }
                else if (info.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                else
                {
                    mfaCode += info.KeyChar;
                    Console.Write("*");
                }
            }
            return mfaCode;
        }

19 Source : Program.cs
with MIT License
from AyrA

private static ConsoleKey WaitForKey()
        {
            Console.Error.WriteLine("Press any key to continue...");
            while (Console.KeyAvailable) { Console.ReadKey(true); }
            return Console.ReadKey(true).Key;
        }

19 Source : ConsoleUtils.cs
with MIT License
from azist

public static string ReadPreplacedword(char subsreplacedute)
    {
      string buff = string.Empty;

      while (true)
      {
        char c = System.Console.ReadKey(true).KeyChar;
        if (Char.IsControl(c)) return buff;
        buff += c;

        if (subsreplacedute != (char)0)
          System.Console.Write(subsreplacedute);

      }
    }

19 Source : ConsoleUtils.cs
with MIT License
from azist

public static SecureBuffer ReadPreplacedwordToSecureBuffer(char subsreplacedute)
    {
      var result = new SecureBuffer();

      while (true)
      {
        char c = System.Console.ReadKey(true).KeyChar;
        if (Char.IsControl(c))
        {
          result.Seal();
          return result;
        }

        var buf = Encoding.UTF8.GetBytes(new char[]{ c });

        for(var i=0; i< buf.Length; i++)
          result.Push(buf[i]);

        Array.Clear(buf, 0, buf.Length);

        if (subsreplacedute != (char)0)
          System.Console.Write(subsreplacedute);

      }
    }

19 Source : ApplicationHostProgramBody.cs
with MIT License
from azist

public static int InteractiveConsoleMain(BootArgs args)
    {
      var result = interactiveConsoleMainBody(args);

      if (System.Diagnostics.Debugger.IsAttached)
      {
        Console.WriteLine("Press any key to stop the debugging...");
        Console.ReadKey(true);
      }

      return result;
    }

19 Source : ProgramBody.cs
with MIT License
from azist

private static void getEntropy()
    {
      var count = Ambient.Random.NextScaledRandomInteger(47, 94);
      ConsoleUtils.Info("Acquiring entropy from user...");
      Console.WriteLine();
      ConsoleUtils.WriteMarkupContent(
@"<push>
<f color=magenta>Please make <f color=white>{0}<f color=magenta> random keystrokes
Do not hit the same key and try to space key presses in time:<pop>
".Args(count));

      var pnow = Stopwatch.GetTimestamp();

      Console.WriteLine();
      for (var i = 0; i < count; i++)
      {
        var k = Console.ReadKey(true).KeyChar;
        if (k < 0x20) continue;
        var now = Stopwatch.GetTimestamp();
        var elapsed = (int)(39621 * (k - 0x19) * (now - pnow));
        pnow = now;
        Ambient.Random.FeedExternalEntropySample(elapsed);
        Console.Write("\r{0}  {1} characters to go ...", elapsed, count - i - 1);
      }
      ConsoleUtils.Info("OK. Entropy key entered");
      Console.WriteLine("-----------------------");
      System.Threading.Thread.Sleep(3000);
      while (Console.KeyAvailable) Console.ReadKey(true);
    }

19 Source : TestRunner.cs
with MIT License
from AzureAD

private Task CreateStopProcessingByUserRequestTask(CancellationTokenSource tokenSource)
        {
            return Task.Run(async () =>
            {
                while (!tokenSource.Token.IsCancellationRequested)
                {
                    try
                    {
                        await Task.Delay(_options.UserInputCheckDelayInMilliseconds, tokenSource.Token);
                    }
                    catch (TaskCanceledException)
                    {
                        // Ignore this exception. In this case task cancellation is the same as running to completion.
                    }

                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                        if (keyInfo.Key == ConsoleKey.Escape)
                        {
                            tokenSource.Cancel();
                            Console.WriteLine("Processing stopped. User cancelled.");
                        }
                    }
                }
            }, tokenSource.Token);
        }

19 Source : Program.cs
with MIT License
from AzureCosmosDB

public static async Task Main(string[] args)
        {
            bool exit = false;
            while (exit == false)
            {
                Console.Clear();
                Console.WriteLine($"Cosmos DB Modeling and Parreplacedioning Demos");
                Console.WriteLine($"-----------------------------------------");
                Console.WriteLine($"[a]   Query for single customer");
                Console.WriteLine($"[b]   Point read for single customer");
                Console.WriteLine($"[c]   List all product categories");
                Console.WriteLine($"[d]   Query products by category id");
                Console.WriteLine($"[e]   Update product category name");
                Console.WriteLine($"[f]   Query orders by customer id");
                Console.WriteLine($"[g]   Query for customer and all orders");
                Console.WriteLine($"[h]   Create new order and update order total");
                Console.WriteLine($"[i]   Delete order and update order total");
                Console.WriteLine($"[j]   Query top 10 customers");
                Console.WriteLine($"-------------------------------------------");
                Console.WriteLine($"[k]   Create databases and containers");
                Console.WriteLine($"[l]   Upload data to containers");
                Console.WriteLine($"[m]   Delete databases and containers");
                Console.WriteLine($"-------------------------------------------");
                Console.WriteLine($"[x]   Exit");

                ConsoleKeyInfo result = Console.ReadKey(true);

                if (result.KeyChar == 'a')
                {
                    Console.Clear();
                    await QueryCustomer();
                }
                else if (result.KeyChar == 'b')
                {
                    Console.Clear();
                    await GetCustomer();
                }
                else if (result.KeyChar == 'c')
                {
                    Console.Clear();
                    await ListAllProductCategories();
                }
                else if (result.KeyChar == 'd')
                {
                    Console.Clear();
                    await QueryProductsByCategoryId();
                }
                else if (result.KeyChar == 'e')
                {
                    Console.Clear();
                    await QueryProductsForCategory();
                    await UpdateProductCategory();
                    await QueryProductsForCategory();
                    await RevertProductCategory();
                }
                else if (result.KeyChar == 'f')
                {
                    Console.Clear();
                    await QuerySalesOrdersByCustomerId();
                }
                else if (result.KeyChar == 'g')
                {
                    Console.Clear();
                    await QueryCustomerAndSalesOrdersByCustomerId();
                }
                else if (result.KeyChar == 'h')
                {
                    Console.Clear();
                    await CreateNewOrderAndUpdateCustomerOrderTotal();
                }
                else if (result.KeyChar == 'i')
                {
                    Console.Clear();
                    await DeleteOrder();
                }
                else if (result.KeyChar == 'j')
                {
                    Console.Clear();
                    await GetTop10Customers();
                }
                else if (result.KeyChar == 'k')
                {
                    // Create databases and containers
                    await Deployment.CreateDatabase(client);
                    Console.Clear();
                    
                }
                else if (result.KeyChar == 'l')
                {
                    //Upload data to containers
                    await Deployment.LoadDatabase(client);
                    Console.Clear();
                }
                else if (result.KeyChar == 'm')
                {
                    //Delete databases and containers
                    await Deployment.DeleteDatabase(client);
                    Console.Clear();
              
                }
                else if (result.KeyChar == 'x')
                {
                    exit = true;
                }
            }

        }

19 Source : ReadLine.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

private static string GetText(KeyHandler keyHandler)
        {
            ConsoleKeyInfo keyInfo = Console.ReadKey(true);
            while (keyInfo.Key != ConsoleKey.Enter)
            {
                keyHandler.Handle(keyInfo);
                keyInfo = Console.ReadKey(true);
            }

            Console.WriteLine();
            return keyHandler.Text;
        }

19 Source : Program.cs
with MIT License
from badamczewski

static KeyBuffer ProcessKeyEvents(string prompt, char breakKey, char multiLineKey, bool wasMultiline = false)
        {
            XConsole.Write(prompt);
            StringBuilder statementBuilder = new StringBuilder();
            XConsole.ForegroundColor = Colors.Green;

            var keyInfo = new ConsoleKeyInfo();
            int bufferIndex = 0;
            int baseIndex = prompt.Length;
            bool isTerminated = false;
            bool isMultiLine = wasMultiline;

            while (keyInfo.KeyChar != breakKey)
            {
                keyInfo = Console.ReadKey(true);
                            
                if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    if (historyIndex > 0) historyIndex--;
                    var historyStatement = history[historyIndex];

                    if (historyStatement != null)
                    {
                        Console.SetCursorPosition(baseIndex, Console.CursorTop);
                        XConsole.Write(new string(' ', statementBuilder.Length + historyStatement.Length));
                        Console.SetCursorPosition(baseIndex, Console.CursorTop);

                        if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift))
                        {
                            XConsole.Write(statementBuilder.ToString() + historyStatement);
                            statementBuilder.Append(statementBuilder.ToString() + historyStatement);
                        }
                        else
                        {
                            //
                            // The statement needs to be colorized.
                            //
                            ColorizeExpression(historyStatement);
                            statementBuilder.Clear();
                            statementBuilder.Append(historyStatement);
                        }
                    }

                    bufferIndex = statementBuilder.Length;

                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    if (historyIndex < history.Length) historyIndex++;
                    var historyStatement = history[historyIndex & history.Length];

                    Console.SetCursorPosition(baseIndex, Console.CursorTop);
                    XConsole.Write(new string(' ', statementBuilder.Length));
                    Console.SetCursorPosition(baseIndex, Console.CursorTop);

                    ColorizeExpression(historyStatement);
                    statementBuilder.Clear();
                    statementBuilder.Append(historyStatement);
                    bufferIndex = statementBuilder.Length;
                }
                else if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    if (bufferIndex == 0)
                        continue;

                    Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                    bufferIndex--;

                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    if (bufferIndex >= statementBuilder.Length)
                        continue;

                    Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
                    bufferIndex++;
                }
                else if (keyInfo.Key == ConsoleKey.Backspace)
                {
                    if (bufferIndex == 0)
                        continue;

                    if (bufferIndex >= statementBuilder.Length)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        XConsole.Write(" ");
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);

                        statementBuilder.Remove(statementBuilder.Length - 1, 1);
                    }
                    else
                    {
                        RemoveBetween(statementBuilder, keyInfo.KeyChar, bufferIndex);
                    }

                    bufferIndex--;

                }
                else if(keyInfo.KeyChar == breakKey)
                {
                    //
                    // This is not an empty key so we need to display it.
                    //
                    if (keyInfo.Key != ConsoleKey.Enter)
                    {
                        statementBuilder.Append(keyInfo.KeyChar);
                        XConsole.Write(keyInfo.KeyChar.ToString());
                    }

                    isTerminated = true;
                    break;
                }
                //
                // Enable multiline mode.
                //
                else if(keyInfo.KeyChar == multiLineKey)
                {
                    statementBuilder.Append(multiLineKey + Environment.NewLine);
                    XConsole.WriteLine(multiLineKey.ToString());

                    isMultiLine = true;
                    break;
                }
                //
                // Move to new line and break here.
                //
                else if (isMultiLine && keyInfo.Key == ConsoleKey.Enter)
                {
                    statementBuilder.Append(Environment.NewLine);
                    XConsole.WriteLine();
                    break;
                }
                else
                {
                    Colorize(keyInfo.KeyChar);

                    if (bufferIndex >= statementBuilder.Length)
                    {
                        statementBuilder.Append(keyInfo.KeyChar);
                    }
                    else
                    {
                        InsertBetween(statementBuilder, keyInfo.KeyChar, bufferIndex);
                    }

                    bufferIndex++;

                    foreach (var command in Definitions.Commands)
                    {
                        var clsIdx = IndexOf(statementBuilder, command);

                        if (clsIdx >= 0 && bufferIndex <= clsIdx + command.Length)
                        {
                            Console.SetCursorPosition(prompt.Length + clsIdx, Console.CursorTop);
                            XConsole.Write(command, Colors.Blue);
                        }
                    }

                }
            }

            return new KeyBuffer() { Statement = statementBuilder.ToString(), IsTerminated = isTerminated, IsMultiLine = isMultiLine};
        }

19 Source : MinecraftServer.cs
with MIT License
from baibao132

public static void server(string ip,int port)
            {

                var client = new TcpClient();
                var task = client.ConnectAsync(ip, port);
                Console.WriteLine("Connecting to Minecraft server..");

                while (!task.IsCompleted)
                {
#if DEBUG
                    Debug.WriteLine("Connecting..");
#endif
                    Thread.Sleep(250);
                }

                if (!client.Connected)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Unable to connect to the server");
                    Console.ResetColor();
                    Console.ReadKey(true);
                    Environment.Exit(1);
                }

                _buffer = new List<byte>();
                _stream = client.GetStream();
                Console.WriteLine("Sending status request");


                /*
                 * Send a "Handshake" packet
                 * http://wiki.vg/Server_List_Ping#Ping_Process
                 */
                WriteVarInt(47);
                WriteString(ip);
                WriteShort((short)port);
                WriteVarInt(1);
                Flush(0);

                /*
                 * Send a "Status Request" packet
                 * http://wiki.vg/Server_List_Ping#Ping_Process
                 */
                Flush(0);

                /*
                 * If you are using a modded server then use a larger buffer to account, 
                 * see link for explanation and a motd to HTML snippet
                 * https://gist.github.com/csh/2480d14fbbb33b4bbae3#gistcomment-2672658
                 */
                var buffer = new byte[Int16.MaxValue];
                // var buffer = new byte[4096];
                _stream.Read(buffer, 0, buffer.Length);

                try
                {
                    var length = ReadVarInt(buffer);
                    var packet = ReadVarInt(buffer);
                    var jsonLength = ReadVarInt(buffer);
#if DEBUG
                    Console.WriteLine("Received packet 0x{0} with a length of {1}", packet.ToString("X2"), length);
#endif
                    var json = ReadString(buffer, jsonLength);
                    var ping = JsonConvert.DeserializeObject<PingPayload.Root>(json);

                    Console.WriteLine("Software: {0}", ping.version.name);
                    Console.WriteLine("Protocol: {0}", ping.version.protocol);
                    Console.WriteLine("Players Online: {0}/{1}", ping.players.online, ping.players.max);
                    string str = "";
                    for (int i = 0; i < ping.players.sample.Count; i++) {
                        str += "\n" + ping.players.sample[i].name;
                    }
                    Console.WriteLine(str);
                }
                catch (IOException ex)
                {
                    /*
                     * If an IOException is thrown then the server didn't 
                     * send us a VarInt or sent us an invalid one.
                     */
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Unable to read packet length from server,");
                    Console.WriteLine("are you sure it's a Minecraft server?");
#if DEBUG
                    Console.WriteLine("Here are the details:");
                    Console.WriteLine(ex.ToString());
#endif
                    Console.ResetColor();
                }
            }

19 Source : Utility.cs
with MIT License
from bbepis

public static async Task<ConsoleKeyInfo> ReadKeyAsync(CancellationToken cancellationToken = default, bool intercept = false, bool handleConsoleCancel = true, int responsiveness = 100)
		{
			var cancelPressed = false;
			ConsoleCancelEventHandler cancelWatcher = null;

			if (handleConsoleCancel)
			{
				cancelWatcher = (sender, args) =>
				{
					args.Cancel = false;
					cancelPressed = true;
				};

				Console.CancelKeyPress += cancelWatcher;
			}

			try
			{
				while (!cancelPressed && !cancellationToken.IsCancellationRequested)
				{
					if (Console.KeyAvailable)
					{
						return Console.ReadKey(intercept);
					}

					await Task.Delay(
						responsiveness,
						cancellationToken);
				}

				if (cancelPressed)
				{
					throw new TaskCanceledException("Readkey canceled by user input.");
				}

				throw new TaskCanceledException();
			}
			finally
			{
				if (handleConsoleCancel)
					Console.CancelKeyPress -= cancelWatcher;
			}
		}

19 Source : MenuApp.cs
with MIT License
from BEagle1984

private void RunUseCase(IUseCase useCase)
        {
            Console.Clear();
            WriteUseCaseHeader(useCase);

            useCase.Run();

            Console.ForegroundColor = Constants.PrimaryColor;
            Console.Write("\r\nPress any key to continue...");
            ConsoleHelper.ResetColor();
            Console.ReadKey(true);
        }

See More Examples