如何使用不模拟键盘的条码扫描器读取条码?

How to read barcodes with a barcode scanner that does not emulate keyboard?

编辑:好的,所以我继续并制作了一个完全可用的控制台应用程序:

public static void Main(string[] args)
    {
        SerialPort mySerialPort = new SerialPort("COM4");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        Thread.Sleep(100);
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine($"Data Received: {indata}");
        indata = "";
    }

现在的问题是,当我尝试在 UWP 应用程序中执行类似操作时 -

public void InitScanner()
       {
            SerialPort mySerialPort = new SerialPort("COM4")
            {
                BaudRate = 9600,
                Parity = Parity.None,
                StopBits = StopBits.One,
                DataBits = 8,
                Handshake = Handshake.None,
                RtsEnable = true
            };

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

            tBlock_spState.Text = mySerialPort.IsOpen.ToString();

       }

        void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            tBlock_test.Text = indata;
        }

        public MainPage()
        {
            this.InitializeComponent();
            InitScanner();
            

        }

它抛出一个 System.IO.IOException 描述“信号量上的帖子太多”(抱歉翻译,我使用的是捷克语 VS)。有谁知道发生这种情况的原因?又一次,到处都找不到任何东西。


所以,我的任务是编写代码,允许从不像键盘那样工作的条形码扫描仪读取数据并将其写入文本框。我的想法是可以通过 System.IO.Ports.SerialPort class 实现,但我完全不知道如何让它正常工作。我正在 UWP 中处理这个问题。到目前为止我已经试过了

SerialPort sp = new SerialPort("COM4", 9600);

        void MethodName()
    {
        string s;

        if(!sp.IsOpen)
        sp.Open();

        while (sp.BytesToRead > 0)
        {
            s = sp.ReadLine();
            tBlock_test.Text = s;
        }

        sp.Close();
    } 

这就是我结束的地方,不知道下一步该做什么,或者即使这在某种程度上是正确的。同样,基本问题,我知道,但我严重坚持这一点,无法在任何地方找到解决方案。如果能提供任何帮助,我将不胜感激。

我已经在 WPF 模板中重新制作了该应用程序并尝试了此处的答案:SerialPort reading cause error because of not owning thread(委托 + 调用方法)它终于成功了。