0

I want to use ctrl+c as input in console. I can disable the ctrl+c to terminate console. But i cannot use the ctrl+c to get input. how can i get the ctrl+c as input????

Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
{
     var isctrlc = e.SpecialKey == ConsoleSpecialKey.ControlC;
     if (isctrlc)
     {
     e.Cancel = true;
     }
};

k = Console.ReadKey(true);
if((k.Modifiers & ConsoleModifiers.Control) != 0)
{
   if((k.Key & ConsoleKey.C)!=0)
   {
       break;
   }
}
G.suren
  • 107
  • 3
  • 10

1 Answers1

1

You can set e.Cancel=true; in CancelKeyPress event handler. I have tested the following code snippet. It works.

class Program
    {
        static void Main(string[] args)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            while (true)
            {
                Thread.Sleep(100);
                Console.WriteLine("..");
            }
        }


        private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            e.Cancel = true;
            Console.WriteLine("Cancel key trapped. Execution will not terminate.");
        }
    }

Update:

You can use following property to achieve what you want.

Console.TreatControlCAsInput = true;

        while (true)
        {
            var k = Console.ReadKey(true);
            if ((k.Modifiers & ConsoleModifiers.Control) != 0)
            {
                if ((k.Key & ConsoleKey.C) != 0)
                {
                    break;
                }
            }

            Thread.Sleep(100);
            Console.WriteLine("..");
        }
Kamalesh Wankhede
  • 1,475
  • 16
  • 37