Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions mcs/class/corlib/System/Console.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,26 @@ public static class Console
#if !NET_2_1
private class WindowsConsole
{
public static bool ctrlHandlerAdded = false;
private delegate bool WindowsCancelHandler (int keyCode);
private static WindowsCancelHandler cancelHandler = new WindowsCancelHandler (DoWindowsConsoleCancelEvent);

[DllImport ("kernel32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
private static extern int GetConsoleCP ();
[DllImport ("kernel32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
private static extern int GetConsoleOutputCP ();

[DllImport ("kernel32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
private static extern bool SetConsoleCtrlHandler (WindowsCancelHandler handler, bool addHandler);

// Only call the event handler if Control-C was pressed (code == 0), nothing else
private static bool DoWindowsConsoleCancelEvent (int keyCode)
{
if (keyCode == 0)
DoConsoleCancelEvent ();
return keyCode == 0;
}

[MethodImpl (MethodImplOptions.NoInlining)]
public static int GetInputCodePage ()
{
Expand All @@ -60,6 +75,18 @@ public static int GetOutputCodePage ()
{
return GetConsoleOutputCP ();
}

public static void AddCtrlHandler ()
{
SetConsoleCtrlHandler (cancelHandler, true);
ctrlHandlerAdded = true;
}

public static void RemoveCtrlHandler ()
{
SetConsoleCtrlHandler (cancelHandler, false);
ctrlHandlerAdded = false;
}
}
#endif
internal static TextWriter stdout;
Expand Down Expand Up @@ -682,12 +709,22 @@ public static event ConsoleCancelEventHandler CancelKeyPress {
ConsoleDriver.Init ();

cancel_event += value;

if (Environment.IsRunningOnWindows && !WindowsConsole.ctrlHandlerAdded)
WindowsConsole.AddCtrlHandler();
}
remove {
if (ConsoleDriver.Initialized == false)
ConsoleDriver.Init ();

cancel_event -= value;

if (cancel_event == null && Environment.IsRunningOnWindows)
{
// Need to remove our hook if there's nothing left in the event
if (WindowsConsole.ctrlHandlerAdded)
WindowsConsole.RemoveCtrlHandler();
}
}
}

Expand Down