/// <summary>Opens a new serial port connection. /// </summary> /// <exception cref="UnauthorizedAccessException"> /// The exception that is thrown when the operating system denies access /// because of an I/O error or a specific type of security error. /// </exception> /// <exception cref="IOException">The exception that is thrown when an /// I/O error occurs</exception> /// <exception cref="ArgumentOutOfRangeException"> /// The exception that is thrown when the value of an argument is outside /// the allowable range of values as defined by the invoked method. /// </exception> /// <exception cref="ArgumentException"> /// The exception that is thrown when one of the arguments provided to a /// method is not valid. /// </exception> /// <exception cref="InvalidOperationException"> /// The exception that is thrown when a method call is invalid for the /// object's current state. /// </exception> /// <exception cref="InteropException">The COM object was not initialized correctly</exception> public void Open() { if (null != serialPort) { serialDataReceived = AutomationFactory.GetEvent(serialPort, "DataReceived"); serialErrorReceived = AutomationFactory.GetEvent(serialPort, "ErrorReceived"); serialPinChanged = AutomationFactory.GetEvent(serialPort, "PinChanged"); serialDataReceived.EventRaised += OnSerialDataReceived; serialErrorReceived.EventRaised += OnSerialErrorReceived; serialPinChanged.EventRaised += OnSerialPinChanged; serialPort.Open(); } else throw new InteropException(); }
/// <summary>Closes the port connection, sets the /// <see cref="System.IO.Ports.SerialPort.IsOpen"/> Property to false, /// and disposes of the internal <see cref="System.IO.Stream"/> object. /// </summary> public void Close() { if (IsOpen) { serialDataReceived.EventRaised -= OnSerialDataReceived; serialErrorReceived.EventRaised -= OnSerialErrorReceived; serialPinChanged.EventRaised -= OnSerialPinChanged; serialDataReceived = null; serialErrorReceived = null; serialPinChanged = null; serialPort.Close(); } }