Standard Devices


Some of the most common input/output mechanisms available in computer programs are the ubiquitous standard output (stdout), standard input (stdin), and standard error (stderr) streams. These enable applications to very easily print information and obtain input for users. For console applications, these standard streams get hooked up automatically to the console for stdout and stderr, and the keyboard for stdin. The System.Console type provides all of the necessary hooks to use these streams, including the ability to redirect them to custom locations. In particular, it offers:

 public TextWriter Out { get; }   // stdout public TextWriter Error { get; } // stderr public TextReader In { get; }    // stdin 

These are hooked up in different ways depending on what environment you are executing within. For example, Visual Studio redirects the outputs for debugging and trace purposes. Windows Forms applications do not have a traditional console window, and instead redirect the standard devices to null streams. Any program can redirect the above standard devices manually using the following Console APIs:

 void SetOut(TextWriter newOut);     // stdout void SetError(TextWriter newError); // stderr void SetIn(TextReader newIn);       // stdin 

This section covers how to work with these standard devices, both for reading and writing.

Writing to Standard Output and Error

There are two available pipes to which you may write — the stdout and stderr streams — accessed through the Out and Error static properties of Console, respectively. These are both represented as TextWriter instances. Writing to these is exactly like working with any other such writer.

Stdout is for used for normal program output, while stderr should be used to report error conditions. Viewed from a standard MS-DOS prompt, the output for the two will be indistinguishable. The output for each can be piped separately using the 1> and 2> redirections, respectively. (For example, the command program.exe 1>stdout.txt 2>stderr.txt runs program.exe, appending anything written to stdout to a file stdout.txt and anything to stderr to stderr.txt.)

The Console class also provides a number of Write and WriteLine methods that mirror those available on TextWriter. These are simply convenience methods that forward the supplied arguments to stdout, making for less verbose code. Like TextWriter, there are printf-like, format-friendly overloads that replace fragments of text with the method's additional arguments.

Reading from Standard Input

There is a single input pipe for the console, the stdin stream. By default, this is hooked up to the console keyboard. The pipe is accessible as a TextReader through the static In property of Console. Reading from stdin is just like working with any other reader and will by default block on reads until data is available. The static Read and ReadLine methods are simply shortcuts that call through to the underlying TextWriter.

When the console is wired up to the keyboard, any reads will indeed block until input becomes available. Even the Read method, however, does not support reading single characters from the keyboard at a time. The call blocks until a carriage return is entered. You can use the static ReadKey method instead to read individual key presses at a time. Moreover, this function enables you to work with raw information like modifiers (alt, shift, etc.), control characters, and raw key code information.

ReadKey returns a ConsoleKeyInfo structure, containing information about the key press. Key represents the key that was pressed, stored as an enumeration value of type ConsoleKey. If you would like to access the key press information as a character, the KeyChar property turns the key press into the appropriate char value and returns it. Lastly, Modifiers returns a flags enumeration of value ConsoleModifiers, of which the possible values are Alt, Control, and Shift. This represents the possible modifiers that were being held at the time of the key press event.

Console Display Control

In the .NET Framework 2.0, a set of functionality has been integrated into the Console class that was previously only available by P/Invoking to various Win32 functions. We won't discuss them in extreme detail. Instead, here is a summary of these APIs:

  • Clear: Clears the console buffer and positions the caret at position 0,0 on the screen.

  • SetCursorPosition: Moves the cursor to a specific x,y coordinate on the screen.

  • SetBufferSize: Sets the buffer size that can be used for drawing characters that are not visible on the primary surface. The BufferHeight and BufferWidth properties retrieve these values. You can then move the buffer around (MoveBufferArea), or even position the primary window such that the buffer is visible (SetWindowPosition).

  • ForegroundColor and BackgroundColor: These properties take a ConsoleColor enumeration value to control the foreground and background colors for the console. ResetColor resets both colors to the console default.

  • Title: This property can be used to change the title bar for the console window. Similarly, the SetWindowSize function can change the height and width of the window.

  • Beep: This method can be used to cause a PC speaker-style beep. An overload is available which permits you to specify the frequency.

These functions enable you to create early-1990s-style interfaces to show off to your family and friends.

Serial Port

We saw above how to communicate with some of the standard devices available on the system (e.g., stdin, stdout, stderr) that are normally associated with the keyboard and console window. The System.IO.Ports namespace provides functionality to similarly communicate over a serial port. Note that these classes cannot be used to read from or write to a parallel, FireWire, or USB port; the .NET Framework does not provide such functionality in the 2.0 release.

To open a serial port, simply construct a new instance of the SerialPort class. The default no-argument constructor will grab hold of the COM1 port, while the SerialPort(string portName) overload enables you to specify precisely which port to open. The static method GetPortNames returns a string[] of all standard ports available on the system. Of course, there is a whole range of parameters one can supply to the constructor, such as baudRate, parity, dataBits, and stopBits, which are specific to the device you are communicating with.

Once you've constructed a SerialPort with all of the appropriate settings based on your device, calling Open will open the underlying port connection. From this point on, working with a serial port is just like working with any other stream. Most of the methods are identical, and indeed you can access the underlying stream by calling the BaseStream property. I won't discuss serial ports further due to the varying details related to communicating with each particular type of device.




Professional. NET Framework 2.0
Professional .NET Framework 2.0 (Programmer to Programmer)
ISBN: 0764571354
EAN: 2147483647
Year: N/A
Pages: 116
Authors: Joe Duffy

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net