I have a piece of code like this:
public class SerialPortListener
{
#region Properties
public SerialPort _Port { get; set; }
public event EventHandler<SerialDataEventArgs> DataReceived;
#endregion
public void Start()
{
Close();
//todo: get attached COM names...
List<string> names = SerialPort.GetPortNames().ToList();
// todo: for testing, let's pick first...
string name = names.FirstOrDefault();
if (string.IsNullOrEmpty(name))
return; // todo: throw error that no devices are attached...
_Port = new SerialPort(name);
_Port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
_Port.Open();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
string data = port.ReadExisting();
if (DataReceived != null)
DataReceived(this, new SerialDataEventArgs(data));
}
public void Close()
{
if (_Port != null && _Port.IsOpen)
_Port.Close();
}
}
public class SerialDataEventArgs : EventArgs
{
public SerialDataEventArgs(string data)
{
Data = data;
}
/// <summary>
/// Byte array containing data from serial port
/// </summary>
public string Data;
}
where com port name is "COM1", and I have connected a handheld barcode scanner. I noticed that it works only when I put a breakpoint on _Port.Open() and then step over it after which I press continue in the debugger. Then scanning works and DataReceivedHandler is called.
Otherwise it doesn't work and scanner also doesn't get a good read beep. I Tested scanner in the application I got from here ,where it works fine every time.
My question is why doesn't it work every time like in example app and what can be done differently to make it work.
startfunction and if you want to recognize when any device is getting connected and auto start then that's the different question. I can provide code if you want to recognize when any devices are connected to the serial port if you need it.