Click here to Skip to main content
15,891,431 members
Articles / Desktop Programming / Win32

How To Make Hooks on Serial Ports in C#

Rate me:
Please Sign up or sign in to vote.
3.20/5 (6 votes)
16 Sep 2009CDDL2 min read 63.2K   7.2K   35   13
An article on creating serial port hooks in C#
Image 1

Introduction

This C# console program illustrates how to use serial port hooks in C#, in a sense. This is because there’s really no readily available API which provides hooking the serial port unlike windows messages, keyboard, and mouse, etc, in which you can use SetWindowsHookEx API.

Background

So you popped up your favorite inet browser, opened your favorite search engine and type “How do I make hook on serial port in C#?”.

Then your search engine begins to search the vast WWW. Voila!

Unless I’m wrong as I may not have searched the inet long enough to dig one, your search results are not exactly the one’s you’re expecting.

So here’s C# console program that at least illustrates the concept in a very simple example. Firstly, we create a WIN32 serial library (see documentation WIN32 Serial Module.chm ) which provides serial hook interfaces. The serial library takes advantage of the overlap option providing asynchronous I/O thus making the hooks a possibility. Then we import the serial library methods in C#. That’s it.

Using the code

If your interest is to be able to use hardware flow control, this is not the right post for you as the serial library does not provide that functionality in this example. However, with a little patience for a small work, you can extend the existing library to do the job.

So this is an example that provides transparent data transfer from a terminal to the application layer and vice-versa. Yet this does not obstruct you to implement your own messaging protocol (i.e. at its simplest STX + <Data> +STX + LRC).

Just like any other non-static classes, you just need to create an instance of class CommsSerial to use it on your program as shown below:

Note that this console program requires the serial port number to be passed as a program argument.

C#
namespace UsingWIN32SerialHooksInCSharp
{
    class SerialProgram
    {
        private CommsSerial comSerial;        

        private void SerialSimulation(ushort port)
        {
            try
            {
              comSerial = new CommsSerial();

                comSerial.SerialReceptionEvent += 
			delegate(object obj, ComEventArgs comEventArgs)
                {
                    Console.WriteLine("\n---Data available notification----");
                    Console.WriteLine("{0} byte(s) successfully read.", 
						comEventArgs.Length);
                    Console.WriteLine("Data: {0}", comEventArgs.ToString());

                    //
                    // Write data to serial.
                    // In real applications, this could be the response after analyzing
                    // the received data.
                    //
                    byte[] dataToWrite = new byte[] { 0x02, (byte)'T', 
				(byte)'E', (byte)'S', (byte)'T', 0x03 };
                    Console.WriteLine("\nWriting {0} byte(s) of data. \nData: {1}",
                                        dataToWrite.Length,
                                        Conversion.BytesToAsciiHex
					(dataToWrite,dataToWrite.Length)
                                        );
                    //write data
                    comSerial.Write(dataToWrite, (uint)dataToWrite.Length );
                };

                comSerial.SerialTransmitEvent += 
			delegate(object obj, ComEventArgs comEventArgs)
                {
                    Console.WriteLine("\n---Write finished notification----");
                    Console.WriteLine("{0} byte(s) successfully written.", 
							comEventArgs.Length);
                };

                try
                {
                    Console.Write("\nOpening serial COM port...");

                    //Open the serial port
                    comSerial.Open(port,
                                CommsSerial.DataSize.EIGHT_BITS,
                                CommsSerial.ParityBit.NOPARITY,
                                CommsSerial.StopBit.ONESTOPBIT,
                                CommsSerial.BaudRate.CBR_115200
                                );

                    Console.WriteLine("OK!");

                    Console.Write("\nInstalling hooks...");
                    //Install the hooks
                    comSerial.InstallHooks();
                    Console.WriteLine("OK!");

                    do
                    {
                        Console.WriteLine("\nSerial monitor listening...\n");

                        //
                        // Do something
                        //
                        // i.e. maybe until stop button is pressed.
                        // 

                        //Simulate active to inactivated state
                        //Active until 25 seconds timeout expires.                        
                        Thread.Sleep(20000);

                        Console.WriteLine("Closing serial monitor...");

                    } while (false);

                    //Uninstall hooks
                    comSerial.UninstallHooks();

                    //
                    comSerial.Close();
                    Console.WriteLine("Monitor closed.");
                }
                catch (SerialManagedException)
                {
                    //Re-throw exceptions
                    throw;
                }
                catch (Exception)
                {
                    //Re-throw exceptions
                    throw;
                }
            }
            catch (SerialManagedException ex)
            {
                Console.WriteLine("A serial exception occurred.");
                Console.WriteLine(ex.Message);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("An argument exception occurred.");
                Console.WriteLine(ex.Message);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Unknown exception occurred.");
                Console.WriteLine(ex.Message);
            }
        }

        static void Main(string[] args)
        {
            ushort port;

            if (args.Length==0)
            {
                Console.WriteLine("\nError: No program argument provided!");
                Console.WriteLine("\nUsage: {0} [serial port]", 
                                    Path.GetFileName
				(Process.GetCurrentProcess().MainModule.FileName)
                                    );
                Console.WriteLine("\n");
                Console.ReadKey();
                return;
            }

            port = Convert.ToUInt16(args[0]);
            if ( port == 0 || port > 15)
            {
                //Default port
                port = 1;
            }            

            SerialProgram serialProgram = new SerialProgram();
            //Perform serial simulation
            serialProgram.SerialSimulation(port);

            //Simulation has ended.
            Console.WriteLine("\nSimulation finished.");
            Console.WriteLine("<press>");
            Console.ReadKey();        
        }
    }
}

History

  • Initial code version 1.0

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


Written By
Software Developer Welcome Real Time
Singapore Singapore
I'm just another guy who has some of passion writing pieces of usable codes.

An embedded developer/systems analyst by profession specializing on EFT-POS and smart cards. And sometimes a business solutions free lancer.

Comments and Discussions

 
BugComplete waist of time. Pin
Eitan Michaelson26-Mar-22 23:18
Eitan Michaelson26-Mar-22 23:18 
QuestionHooking? Pin
burnm42010-Oct-15 13:47
burnm42010-Oct-15 13:47 
QuestionIs a port sniffer? PinPopular
eyanson10-Feb-15 22:43
eyanson10-Feb-15 22:43 
Hi. I need a code to snif serial port and send captured packets to a file.
This code is usefule for this purpose?
On wich platforms works?

Thanks
QuestionShared access Pin
renatoferreirarenatoferreira22-Sep-14 11:08
renatoferreirarenatoferreira22-Sep-14 11:08 
Questionaa Pin
Member 1041072013-Feb-14 0:54
Member 1041072013-Feb-14 0:54 
Questionx64 version Pin
validol6-Oct-11 2:13
validol6-Oct-11 2:13 
AnswerRe: x64 version Pin
parnet12-Dec-13 19:13
parnet12-Dec-13 19:13 
Generalhi,can the hooks be used to log comunication? [modified] Pin
simion31427-Sep-10 1:55
simion31427-Sep-10 1:55 
GeneralHelp file won't display Pin
Dave Cross10-Jan-10 0:35
professionalDave Cross10-Jan-10 0:35 
GeneralRe: Help file won't display Pin
Crisanto T. Cafirma17-Jan-10 16:59
Crisanto T. Cafirma17-Jan-10 16:59 
GeneralModifying The Data Stream Pin
Doug Richards28-Oct-09 16:04
Doug Richards28-Oct-09 16:04 
GeneralVery interesting! Pin
reinaldohf17-Sep-09 12:59
reinaldohf17-Sep-09 12:59 
GeneralMy vote of 2 Pin
Dave Kreskowiak17-Sep-09 2:14
mveDave Kreskowiak17-Sep-09 2:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.