0

更新

我正在阅读RFID Card,并将其价值签入我的textbox.text.
它在我第一次通过我的卡时工作RFID Reader,但在我第二次通过卡时,它会在我的卡上显示整个卡的 ID textbox.text,它只显示卡 ID 的最后一个字母。有时您会看到整个数字在文本框中出现和消失的速度非常快,但是从您第二次通过卡片开始,文本框中只剩下最后一个字母。
这可能是什么原因造成的?

这是我当前的代码:

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

namespace RFID_Reader
{
    public partial class PortaSerial : Form
    {
        private SerialPort porta_serial = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);


        public PortaSerial()
        {
            InitializeComponent();
        }

        private void PortaSerial_Load(object sender, EventArgs e)
        {
            try
            {
                if (porta_serial.IsOpen)
                {
                    porta_serial.Close();
                }
                porta_serial.Open();
                porta_serial.DtrEnable = true;
                porta_serial.DataReceived += new SerialDataReceivedEventHandler(Recebe_Data);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        void Recebe_Data(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {               
                string oi = porta_serial.ReadExisting().ToString();
                SetLabel(oi);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        void SetLabel(String s)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action<String>(SetLabel), s);
                    return;
                }
                textBox1.Text = RemoveSpecialCharacters(s);           
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }       

        public static string RemoveSpecialCharacters(string str)
        {
            StringBuilder sb = new StringBuilder();            
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }
    }
}
4

2 回答 2

4

为了访问 GUI 的元素(文本框、标签等),您需要在 UI 线程中运行。DataReceived 正在另一个线程中运行。您可以像这样通过调用更改为 UI 线程

void SetLabel(String s)
{
   if (this.InvokeRequired) {
      this.Invoke (new Action<String>(SetLabel), s);
      return;
   }

   Label1.Text = s;
}

但要注意——如果您需要访问 GUI 的不同部分(例如标签文本框),您应该“收集”这些调用,因为每次调用都需要一些时间。您也可以考虑使用 BeginInvoke 而不是 Invoke 来阻止接收线程。但是,您应该在 MSDN 或 google 中阅读这些详细信息以获取更难的示例。

于 2013-05-14T18:53:08.270 回答
0

在您的 Form1_Load 方法中,您使用port来引用您的SerialPort对象,但在您的事件处理程序中,您使用porta_serial.

于 2013-05-14T18:25:35.307 回答