9.20 Access a COM Port


Problem

You need to send data directly to a serial port.

Solution

The Win32 API provides unmanaged methods in the kernel32.dll library for directly reading and writing bytes to and from a serial port. You can import these functions into your C# application or use the higher-level Microsoft Communications ActiveX control (MSComm.ocx), which is a licensed control included with Microsoft Visual Studio 6.

Discussion

Unfortunately, .NET does not provide any managed interface for dealing with serial ports. As a result, developers who need this functionality will probably need to dive into some relatively complex interop coding.

One solution is to generate a .NET wrapper for the Microsoft Communications Control (MSComm.ocx). It provides a higher-level object model for working with serial ports. However, you must obtain this control through Visual Studio 6 to develop with it because it's a licensed control. (You can do a custom install of Visual Studio 6 and install only the ActiveX components , which require approximately 5 MB of disk space.) For more information, refer to the Visual Studio 6 documentation.

Another option is to import the API functions from kernel32.dll. This method requires some additional care because you must be careful to use the correct C# data types and preserve the layout of the memory structures. Fortunately, Justin Harrell (jharrell@aciss.com) has provided a solution to this problem with a custom C# class named ComPort that exposes this functionality. The full code for this class is fairly long and is available with the sample code for this recipe.

You can add this class to your applications and use the following code to interact with a COM port:

 ComPort port = new ComPort(); try {     // Configure baud rate, parity, etc.     port.BaudRate = 9600;     port.Parity = 0;     port.PortNum = 1;     port.ReadTimeout = 10;     port.StopBits = 1;     port.ByteSize = 1;     // Open the port.     port.Open();     // Write some data.     port.Write(new byte[1]);     // Close the port.     port.Close(); }catch (ApplicationException err) {     Console.WriteLine(err.Message); } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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