Link to home
Start Free TrialLog in
Avatar of suwanee
suwanee

asked on

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,
Avatar of Smacky311
Smacky311

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.
Avatar of Fernando Soto
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

Avatar of suwanee

ASKER

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?
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of suwanee

ASKER

Thanks again
Avatar of suwanee

ASKER

|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.
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.
Avatar of suwanee

ASKER

Understand now. Thanks again.
Not a problem, glad to help. ;=)