using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; using System.IO; using System.IO.Ports; using System.Runtime.InteropServices; namespace PortMon { public partial class PortMon : ServiceBase { public static string buf; public PortMon() { InitializeComponent(); buf = ""; } [DllImport("kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); public delegate bool HandlerRoutine(CtrlTypes CtrlType); // define the enum for the control event types public enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT=5, CTRL_SHUTDOWN_EVENT } // the handler function for the control event private static bool CtrlCheck(CtrlTypes ctrlType) { if (ctrlType == CtrlTypes.CTRL_LOGOFF_EVENT) return false; return true; } protected string splitStr(string ins) { // split the incoming string into lines including empty lines string[] rows = ins.Split('\n'); // output the lines whereever we need them for (int i = 0; i < rows.Length - 1; i++) { string text = rows[i] + ",date=" + DateTime.Now.ToString()+"\r\n"; File.AppendAllText("c:\\portlog.txt", text); } // look for a timeout as well if there is a too long break // mark the time for this occasion // return the last line fragment return rows[rows.Length - 1]; } protected void OnReceive(object sender, SerialDataReceivedEventArgs e) { SerialPort com = (SerialPort)sender; buf += com.ReadExisting(); buf = splitStr(buf); } protected override void OnStart(string[] args) { // do a discovery of portnames string[] portnames = SerialPort.GetPortNames(); foreach (string s in portnames) { File.AppendAllText("c:\\portlog.txt", "<"+s+">\r\n"); } string port = "COM3"; if (args.Length >= 1) { port = args[0]; } myComPort.PortName = port; myComPort.Open(); SetConsoleCtrlHandler(new HandlerRoutine(CtrlCheck), true); // write log to file string text = "#Service started on port " + port + " at "; text += DateTime.Now.ToString() + "\r\n"; File.AppendAllText("c:\\portlog.txt", text); } protected override void OnStop() { // write log to file string text = "#Service stopped at " + DateTime.Now.ToString() + "\r\n"; File.AppendAllText("c:\\portlog.txt", text); } } }