keyboard input from the user to halt the program (C#)

Dear all,

I am trying to use a keyboard input from the user to halt the program as such

static void ctrlc(){running = 0;}

in the main function
{...while (running)
{...capture data and write to file}
}

I chanced upon this URL in MSDN and copy the code into my C# VS.net 2005 version 1.1 software to run. But it cant compile saying "The type or namespace name 'ConsoleCancelEventArgs' could not be found(are you missing a using directive or assembly reference )"

URL: http://msdn2.microsoft.com/en-us/library/xcw9277d


Does someone know what is the problem

Thank you very much.

Regards,
Siew eng


Answer this question

keyboard input from the user to halt the program (C#)

  • Tom Nunamaker

    Are you compiling against the 2.0 version of .NET   It was added in 2.0.  If you can post your code causing the problem it might help someone come up with a reason you're seeing the problem.

    Nonetheless the skeleton code would be:

    using System;

    class App
    {
       private bool running = true;

       private void OnCancelApp ( object sender, ConsoleCancelEventArgs e )
       {
          running = false;
       }

       static void Main ( )
       {
          //Hook into console cancellation
         Console.CancelKeyPress += OnCancelApp;

          while (running)
          {
             //Do work
          };
        }
    }
    Michael Taylor - 10/12/05

  • keyboard input from the user to halt the program (C#)