Click here to Skip to main content
Click here to Skip to main content

Producing KeyPress events for the Console

, 23 Nov 2011
Rate this:
Please Sign up or sign in to vote.
A C# class to raise KeyPress events for use in Console Applications
This class is in response to this question: http://www.codeproject.com/Forums/1649/Csharp.aspx?fid=1649&tid=4084628[^] . I doubt I'll actually use this code in a real application, but it was an interesting exercise, perhaps the techniques used will be of interest to others.
 
This is a static class that spins off a Thread to perform System.Console.ReadKey and raise the KeyPress event as required. Three fields are required: one to hold a reference to the Thread, one to hold the event handlers, and one to allow locking to avoid threading problems.
 
namespace PIEBALD.Types
{
  public static partial class Consolation
  {
    private static System.Threading.Thread thread ;
 
    private static System.Windows.Forms.KeyPressEventHandler watchers ;
 
    private static readonly object pickle ;
 
    static Consolation
    (
    )
    {
      pickle = new object() ;
 
      thread = null ;
 
      return ;
    }
  }
}
 
The only public member is the KeyPress event; it has custom accessors because add needs to spin off the Thread when necessary. The Thread only executes as long as there are handlers attached to the event.
 
public static event System.Windows.Forms.KeyPressEventHandler
KeyPress
{
  add
  {
    lock ( pickle )
    {
      watchers += value ;
    }
 
    if ( thread == null )
    {
      thread = new System.Threading.Thread ( DoRead )
      {
        Priority = System.Threading.ThreadPriority.BelowNormal
      ,
        IsBackground = true
      } ;
 
      thread.Start() ;
    }
 
    return ;
  }
 
  remove
  {
    lock ( pickle )
    {
      watchers -= value ;
    }
 
    return ;
  }
}
 
The only other member of the class is the DoRead method that executes on the Thread as long as there are handlers.
 
private static void
DoRead
(
)
{
  try
  {
    /* Clear existing characters from the buffer */
    while ( System.Console.KeyAvailable )
    {
      System.Console.ReadKey ( true ) ;
    }
 
    while ( true )
    {
      lock ( pickle )
      {
        if ( watchers == null )
        {
          break ;
        }
 
        while ( System.Console.KeyAvailable )
        {
          watchers ( null , new System.Windows.Forms.KeyPressEventArgs
            ( System.Console.ReadKey ( true ).KeyChar ) ) ;
        }
      }
 
      System.Threading.Thread.Sleep ( 10 ) ;
    }
  }
  catch
  {
    /* Just let the thread exit neatly */
  }
  finally
  {
    thread = null ;
  }
 
  return ;
}
 
To test the class, I used the following code. It displays the character in c every second until that character is Z, the value of c is updated by the KeyPress event handler.
 
public static partial class Template
{
  private static char c = ' ' ;
 
  [System.STAThreadAttribute()]
  public static int
  Main
  (
    string[] args
  )
  {
    int result = 0 ;
 
    try
    {
      PIEBALD.Types.Consolation.KeyPress += MyHandler ;
 
      while ( c != 'Z' )
      {
        System.Console.Write ( c ) ;
 
        System.Threading.Thread.Sleep ( 1000 ) ;
      }
    }
    catch ( System.Exception err )
    {
      System.Console.WriteLine ( err ) ;
    }
    finally
    {
      PIEBALD.Types.Consolation.KeyPress -= MyHandler ;
    }
 
    return ( result ) ;
  }
 
  private static void
  MyHandler
  (
    object                                 sender
  ,
    System.Windows.Forms.KeyPressEventArgs e
  )
  {
    c = e.KeyChar ;
 
    return ;
  }
}
 
I expect that simply using System.Console.KeyAvailable and System.Console.ReadKey would be enough for most real-workd situations, but if you really want to use events, this code might provide a basis for an implementation.

License

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

About the Author

PIEBALDconsult
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology
 
Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.
 
OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB
 
---------------
 
"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]
 
"Typing is no substitute for thinking." -- R.W. Hamming
 
"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup
 
ZagNut’s Law: Arrogance is inversely proportional to ability.
 
"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon
 
"linq'ish" sounds like "inept" in German -- Andreas Gieriet
 
"Things would be different if I ran the zoo." -- Dr. Seuss
 
"Wrong is evil, and it must be defeated." – Jeff Ello
 
"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw
 
“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Omit needless local variables." -- Strunk... had he taught programming
 

 
"We learn more from our mistakes than we do from getting it right the first time."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 23 Nov 2011
Article Copyright 2011 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid