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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Fernando SotoRetiredCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.