Click here to Skip to main content
15,889,176 members
Articles / Programming Languages / C#
Tip/Trick

Producing KeyPress events for the Console

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
23 Nov 2011CPOL1 min read 26K   3  
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)


Written By
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

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

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"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

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

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

Comments and Discussions

 
-- There are no messages in this forum --