c#Substring sendkeys

时间:2015-08-05 09:47:24

标签: c# serial-port substring sendkeys

我有 RFID-Reader ,想要读取串口收到的数据。只要我不使用Substring,这就可以正常工作。

当我使用Substring时,我收到一条带有来自COM-Port的第二个输入的错误消息。

我怎样才能让它发挥作用? SendKeys 仅发送"击键"还是发送一个字符串?

using System;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;

namespace SerialToKeyboard.Control
{
class ComToKey : IDisposable
{
    private readonly SerialPort _port;

    public ComToKey(SerialPort port)
    {
        _port = port;
        _port.DataReceived += PortOnDataReceived;
    }

    /// <summary>
    /// Event thrown whenever the serial port received data
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PortOnDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (_port.BytesToRead > 0)
        {
            // PostKeys
            var original = _port.ReadExisting();
            original = original.Substring(0, 11);
            // Reformat string to fit SendKeys()
            var reformattedString = DefaultFormatter.Reformat(original);
            try
            {
                SendKeys.SendWait(reformattedString);
            }
            // Handle exception caused if keys are sent to an application
            // not handling keys
            catch(InvalidOperationException)    
            {
            }
        }
    }

    public void Start()
    {
        if (!_port.IsOpen)
            _port.Open();
    }
    public void Stop()
    {
        if (_port.IsOpen)
            _port.Close();
    }
    public void Dispose()
    {
        if (_port.IsOpen)
            _port.Close();
        _port.DataReceived -= PortOnDataReceived;
        _port.Dispose();

    }
}
}

0 个答案:

没有答案