Subscribing to cancel key press events in a .NET console application

Users can stop and close a console application by any of the following methods:

  • Pressing the ‘x’ button in the top right hand corner
  • Pressing ctrl+c
  • Pressing ctrl+break

Occasionally you might want to check whether the user has pressed either ctrl+c or ctrl+break. The following code sample will show you how to do that.

The Console object has an event called CancelKeyPress that you can subscribe to. The following sample adds an event handler to this event. The handler prints the special key property of the ConsoleCancelEventArgs object. It can have 2 values: ControlC or ControlBreak. Then if ctrl+c was pressed then the event is cancelled, i.e. the console window won’t close:

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

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
	Console.WriteLine(e.SpecialKey);
	if (e.SpecialKey == ConsoleSpecialKey.ControlC)
	{
		e.Cancel = true;
	}
}

The Console_CancelKeyPress method will be called if you press either the ctrl+c or the ctrl+break key combination.

View all various C# language feature related posts here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: