Click here to Skip to main content
12,511,648 members (45,489 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15.5K views
3 bookmarked
Posted

Producing KeyPress events for the Console

, 23 Nov 2011 CPOL
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)

Share

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, acknowledged pedant and contrarian

---------------

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"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

You may also be interested in...

Pro
Pro

Comments and Discussions

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