Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Producing KeyPress events for the Console

5.00/5 (2 votes)
23 Nov 2011CPOL1 min read 26.4K  
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)