Click here to Skip to main content
12,761,464 members (35,055 online)
Click here to Skip to main content
Add your own
alternative version


34 bookmarked
Posted 16 Sep 2009

How To Make Hooks on Serial Ports in C#

, 17 Sep 2009 CDDL
Rate this:
Please Sign up or sign in to vote.
An article on creating serial port hooks in C#


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.


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.

namespace UsingWIN32SerialHooksInCSharp
    class SerialProgram
        private CommsSerial comSerial;        

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

                comSerial.SerialReceptionEvent += 
			delegate(object obj, ComEventArgs comEventArgs)
                    Console.WriteLine("\n---Data available notification----");
                    Console.WriteLine("{0} byte(s) successfully read.", 
                    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}",
                    //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.", 

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

                    //Open the serial port


                    Console.Write("\nInstalling hooks...");
                    //Install the hooks

                        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.                        

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

                    } while (false);

                    //Uninstall hooks

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

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

            if (args.Length==0)
                Console.WriteLine("\nError: No program argument provided!");
                Console.WriteLine("\nUsage: {0} [serial port]", 

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

            SerialProgram serialProgram = new SerialProgram();
            //Perform serial simulation

            //Simulation has ended.
            Console.WriteLine("\nSimulation finished.");


  • Initial code version 1.0


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


About the Author

Crisanto T. Cafirma
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.

You may also be interested in...

Comments and Discussions

QuestionHooking? Pin
burnm42010-Oct-15 14:47
memberburnm42010-Oct-15 14:47 
QuestionIs a port sniffer? Pin
eyanson10-Feb-15 23:43
membereyanson10-Feb-15 23:43 
QuestionShared access Pin
renatoferreirarenatoferreira22-Sep-14 12:08
memberrenatoferreirarenatoferreira22-Sep-14 12:08 
Questionaa Pin
Member 1041072013-Feb-14 1:54
memberMember 1041072013-Feb-14 1:54 
Questionx64 version Pin
validol6-Oct-11 3:13
membervalidol6-Oct-11 3:13 
AnswerRe: x64 version Pin
parnet12-Dec-13 20:13
memberparnet12-Dec-13 20:13 
Generalhi,can the hooks be used to log comunication? [modified] Pin
simion31427-Sep-10 2:55
membersimion31427-Sep-10 2:55 
GeneralHelp file won't display Pin
Dave Cross10-Jan-10 1:35
memberDave Cross10-Jan-10 1:35 
GeneralRe: Help file won't display Pin
Crisanto T. Cafirma17-Jan-10 17:59
memberCrisanto T. Cafirma17-Jan-10 17:59 
GeneralModifying The Data Stream Pin
Doug Richards28-Oct-09 17:04
memberDoug Richards28-Oct-09 17:04 
GeneralVery interesting! Pin
reinaldohf17-Sep-09 13:59
memberreinaldohf17-Sep-09 13:59 
GeneralMy vote of 2 Pin
Dave Kreskowiak17-Sep-09 3:14
mvpDave Kreskowiak17-Sep-09 3: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 17 Sep 2009
Article Copyright 2009 by Crisanto T. Cafirma
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid