Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a console app which I have inherited. This has a CTRL-BREAK handler in place which works fine however I have added in a routine for detecting a CTRL-D keypress but this appears to be absorbing all key press messages effectively wiping out and CTRL-C or CTRL-BREAK messages.

Is there a better way to do this or am I up pooh creek?

What I have tried:

This is part of the CTRL-BREAK handler, pretty standard stuff.
C#
private static bool TermHandlerRoutine(CtrlTypes dwCtrlType)
       {
           switch (dwCtrlType)
           { //no break so all close events handled same
               case CtrlTypes.CTRL_C_EVENT:
               case CtrlTypes.CTRL_CLOSE_EVENT:
               case CtrlTypes.CTRL_BREAK_EVENT:
               case CtrlTypes.CTRL_SHUTDOWN_EVENT:
                   terminated = true;
                   return true;
           }
           return false;
       }
 
       #region unmanaged
       [DllImport("kernel32.dll", SetLastError = true)]
       static extern bool GenerateConsoleCtrlEvent(CtrlTypes sigevent, int dwProcessGroupId);
       [DllImport("kernel32.dll", SetLastError = true)]
       public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
 
       public enum CtrlTypes
       {
           CTRL_C_EVENT = 0,
           CTRL_BREAK_EVENT,
           CTRL_CLOSE_EVENT,
           CTRL_LOGOFF_EVENT = 5,
           CTRL_SHUTDOWN_EVENT = 6
       }


This is the CTRL-D detecting code which resides inside a loop-
C#
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
    {
    if (cki.Key == ConsoleKey.D)
        {
          // do stuff
        }
    }

it detects CTRL-D nicely but seems to absorb all keypresses and not pass on anything else to the CTRL-BREAK handler.
Posted
Updated 1-Mar-16 14:55pm

1 solution

I'm wondering if its because Console.ReadKey() 'blocks' until it actually gets input - a nicer way of doing this may be something like :-

C#
while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo cki = Console.ReadKey();   // There's also a Console.ReadKey(true) variant 
        // Check cki value here 
    }
}
 
Share this answer
 
Comments
Member 11709930 1-Mar-16 21:08pm    
Brilliant. Problem solved and I've learnt a bit more.
thanks
Sergey Alexandrovich Kryukov 1-Mar-16 22:29pm    
Sure, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900