How to catch a key pressed in C# console application?

Hi,

In my console application using C#, I have a infinite loop to process a task. I want to use some methods to catch a specific key pressed (ex: Alt+B) to break from the loop, and do some cleanp-up work before exit the program.

I know Ctrl+C can exit, but it exit to the program immediately without do the clean up. It even doesn't call the finally clause if I hit the Ctrl+C key.

Is there any way to the Key pressed?

Thanks,
suwaneeAsked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi suwanee;

See comments in code snipped.

Fernando
// Place the file variable at class level as shown in below code.
 
    class Program
    {
        private static StreamWriter oMyfile;  // Class level variable
 
        static void Main(string[] args)
        {
 
// Then in the event handler close the file 
 
        protected static void Ctrl_C_Pressed(object sender, ConsoleCancelEventArgs args)
        {
            if (args.SpecialKey == ConsoleSpecialKey.ControlC)
            {
                // Save your work here and when it exits this event handler
                // it will terminate the program
                oMyfile.Close();   // oMyfile is a class level variable  and can be accessed from here to close it.
            }
            else
            {
                // Do not end the program and go back to processing.
                // the Control Break key was pressed
                args.Cancel = true;
            }
        }

Open in new window

0
 
Smacky311Commented:
Due to the complication of overriding keystrokes I'd recommend using a windows application instead of a console application.  Then you can open a tiny Form that and tie the form close event to your cleanup code.
0
 
Fernando SotoRetiredCommented:
Hi suwanee;

If you are using the .Net Framework 2.0 or higher you can use, Console.CancelKeyPress Event"

See sample code below.

Fernando


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Ctrl_C_Pressed);
 
            while (true)
            {
                Console.WriteLine("Hello World");
                Thread.Sleep(3000);
            }
        }
 
        protected static void Ctrl_C_Pressed(object sender, ConsoleCancelEventArgs args)
        {
            if (args.SpecialKey == ConsoleSpecialKey.ControlC)
            {
                // Save your work here and when it exits this event handler
                // it will terminate the program
            }
            else
            {
                // Do not end the program and go back to processing.
                // the Control Break key was pressed
                args.Cancel = true;
            }
        }
    }
}

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
suwaneeAuthor Commented:
Thank you Fernando. You suggest is very helpful. But stil one more question: My clean up jobs include closing a file which is opened. I need to call oMyfile.Close. It looks like I need to pass the oMyfile to the protected static void Ctrl_C_Pressed( ), how can I do that?
0
 
suwaneeAuthor Commented:
Thanks again
0
 
suwaneeAuthor Commented:
|o|,

It didn't compile if I put the "oMyfile.Close();" inside the handle. How can I pass this object inside the handle function protected static void Ctrl_C_Pressed(object sender, ConsoleCancelEventArgs args)?

Thanks again.
0
 
Fernando SotoRetiredCommented:
When you defined the oMyfile did you place it outside of all methods/ functions. and did you remove the original definition. Also make sure that you are using the static keyword as shown below.

private static StreamWriter oMyfile;   // Must be at class level so that you have access to it in ALL code
                                                           // functions.

On your question, "How can I pass this object inside the handle", You can not the delegate that defines this handler is predefined and can not be changed.
0
 
suwaneeAuthor Commented:
Understand now. Thanks again.
0
 
Fernando SotoRetiredCommented:
Not a problem, glad to help. ;=)
0
All Courses

From novice to tech pro — start learning today.