掃描器事件 (POS for .NET v1.14 SDK 文件)
條碼掃描器以非同步方式運作,因此當資料可用或裝置狀態變更時,必須通知應用程式。 您可利用 .NET 委派向應用程式提出事件來執行這項工作。
如裝置輸入與事件主題所討論,事件會先排入佇列才傳遞至應用程式。 The Microsoft Point of Service for .NET (POS for .NET) 基底類別提供方法讓服務物件程式碼將事件排入佇列,以便延遲向應用程式傳遞事件,直到應用程式可對其進行處理為止。 同時,服務物件可繼續等候其他傳入的硬體事件。
掃描器裝置可傳送四個事件至應用程式。 針對其中兩個事件 (DataEvent 與 ErrorEvent),POS for .NET ScannerBase 類別提供受保護的協助程式方法來簡化提出該事件所需的程式碼:
Event | 將事件排入佇列的方法 |
---|---|
DataEvent | 受保護方法 ScannerBase.GoodRead |
ErrorEvent | 受保護方法 ScannerBase.FailedRead |
另外兩個事件 DirectIOEvent 與 StatusUpdateEvent 必須利用較低層級 ScannerBasic 類別的成員來提出。 如需詳細資訊,請參閱裝置輸入與事件。
由於掃描器裝置可隨時傳遞資料至系統,因此掃描器服務物件必須啟動獨立讀取器執行緒,以非同步方式等候資料。 當資料從裝置送達時,事件應從此執行緒排入佇列。
根據裝置輸入提出事件
啟動讀取器執行緒以便等候來自裝置的輸入。
等候讀取器執行緒的輸入,最常使用 Win32 直接函式從 USB 匯流排讀取資料。
當您收到資料之後,請確認資料有效,例如,標頭與資料類型的封包具足夠位元組。
如果資料無效,請呼叫 ScannerBase.FailedScan 方法,將在應用程式提出的 ErrorEvent 事件排入佇列。
如果資料有效,請呼叫 ScannerBase.GoodScan 方法,將最終在應用程式提出的 DataEvent 事件排入佇列 。
範例
一旦從裝置收到輸入,服務物件就會將適當事件排入佇列。 您可透過寫入方法來進行,例如本主題所示範例會從服務物件讀取器執行緒呼叫方法。
// A Service Object may implement a method such as this one to
// be called from the reader thread of the Service Object.
void OnDataScanned(byte[] data)
{
// Ignore input if process in the Error state. There is no
// need to send an ErrorEvent to the application, because it has
// already been notified by this point.
if (State == ControlState.Error)
{
return;
}
// Make sure that the incoming buffer is large enough to contain
// at least the header and type data.
if ((int)data[1] < 5)
{
// By calling FailedRead, you are queueing an
// ErrorEvent for eventual delivery to the application.
FailedScan();
}
else
{
// The buffer received from the device will be longer
// than we need. Therefore, trim it down. Allocate space for
// the number of bytes contained in data[1], plus one
// more for the first byte in the buffer.
byte[] b = new byte[(int)data[1] + 1];
// Copy the data into a new buffer.
for (int i = 0; i <= (int)data[1]; i++)
{
b[i] = data[i];
}
// By calling GoodScan, you are queueing a DataEvent
// which will delivered to the application when it is suitable.
GoodScan(b);
}
}
此範例無法自行編譯,但可插入完整的掃描器服務物件導入。