有一段时间了,我一直试图让我的RFID阅读器自动读取(扫描)一张卡片。虽然我以前的代码,让读者在按下按钮时扫描卡片。但是,我希望能够在现场放置任何卡片后自动连续扫描卡片。这是我试过的。但我无法在文本框中显示扫描的UID。请帮助您。
class CardReader : IDisposable
{
IntPtr _pSnr = Marshal.AllocHGlobal(1024);
private Thread _t;
private Action<string> _callback;
private volatile bool _stop;
public void ReadCard()
{
short icdev = 0x0000;
int status;
byte type = (byte)'A';//mifare one type is A
byte mode = 0x26; // Request the card which is not halted.
ushort TagType = 0;
byte bcnt = 0x04;//mifare hold on 4
IntPtr pSnr;
byte len = 255;
sbyte size = 0;
pSnr = Marshal.AllocHGlobal(1024);
for (int i = 0; i < 2; i++)
{
status = rf_request(icdev, mode, ref TagType);//request card
if (status != 0)
continue;
status = rf_anticoll(icdev, bcnt, pSnr, ref len);//i did anticol--get the card sn
if (status != 0)
continue;
status = rf_select(icdev, pSnr, len, ref size);//select one card
if (status != 0)
continue;
byte[] szBytes = new byte[len];
for (int j = 0; j < len; j++)
{
szBytes[j] = Marshal.ReadByte(pSnr, j);
}
String m_cardNo = String.Empty;
for (int q = 0; q < len; q++)
{
m_cardNo += byteHEX(szBytes[q]);
}
_callback(m_cardNo);
// txtSearchPurse.Text = m_cardNo;
break;
}
}
public void Work()
{
while (!_stop)
{
ReadCard();
Thread.Sleep(1000);
}
}
public void Start(Action<string> cardRead)
{
if (_t != null)
return;
_stop = false;
_callback = cardRead;
_t = new Thread(Work);
_t.Start();
}
public void Stop()
{
if (_t != null)
{
_stop = true;
_t.Join();
_t = null;
}
}
public void Dispose()
{
Marshal.FreeHGlobal(_pSnr);
}
}
我试着像这样使用它:
private void btnRequest_Click(object sender, EventArgs e)
{
var reader = new CardReader();
reader.Start(CardReaded);
}
private void CardReaded(string cardnr){
//txtSearchPurse.Text = _callback;
}
答案 0 :(得分:0)
这是我尝试过的。但我无法在文本框中显示扫描的UID。
所以你的回调成功解雇了吗?你有什么错误,如果有的话?我猜你有一个“跨线程异常”。如果是这样,请按照以下方式修复:
private void CardReaded(string cardnr)
{
this.Invoke((MethodInvoker)delegate
{
txtSearchPurse.Text = cardnr;
});
}