Mark Michaelis' Weblog :
Updated: 9/1/2004; 7:02:28 AM.

 








Subscribe to "Mark Michaelis' Weblog" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.

Subscribe To
Mark's Weblog

 
 

Tuesday, June 03, 2003

System.Console.Read() Doesn't Read a Character Until it Receives a CR/LF
Google Search It

About nine months ago I was teaching a .NET course and it was pointed out to me that System.Console.Read() did not actually read a character until the user pushed ENTER (CR/FL).  Ugghhhh!!  This meant that it was not possible to do character validation within the console so that you could, for example, only allow users to input digits.  You could prompt a user to enter a number and they could enter "two" followed by ENTER and there was no way of preventing it.

To get around this I created a ConsoleEx class that supports a ReadCharacter() function that reads a character and doesn't echo the character to standard out.  This enables the validation on typing functionality that should have been available in the System.Console class.

For a full download of the project and its test go here.

In writing this code I learned a few things about P/Invoke and error handling that  I really should have known but didn't.  Any Win32 API that uses Win32 API GetLastError() to return the error code should assign the SetLastError named parameter of DllImport to true.

[DllImport("kernel32.dll", SetLastError=true)]
private static extern int GetStdHandle(int handle);

This saves off any error so that you can call System.Runtime.InteropServices.Marshal.GetLastWin32Error() to retrieve the last error number.  Better yet, you can throw System.ComponentModel.Win32Exception (no parameters required in the constructor) exception and this will automatically sets the error message using the last error.  Cool! 

By the way, there is a ConsoleEx class on GotDotNet (from Microsoft) that not only supports read character but also changing colors and dynamically moving around in the console window.  Source code is included but (of course) my implementation of ReadCharacter() is better.  :)


10:08:33 PM   []    comment []

© Copyright 2004 Mark Michaelis.



 


June 2003
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
May   Jul


Recent Posts