POS for .NET 完全支援 Windows 嵌入式即插即用技術。 為了使用此功能,服務物件開發者只需在程式碼中加入一個或多個 HardwareId 屬性,或將硬體參考包含在 即插即用的 XML 配置 檔中。
將此屬性加入服務物件有助於應用程式開發者,他們現在會知道,當他們使用 PosExplorer 來取得服務物件清單時,列表中的任何服務物件都會與運作中的 POS 裝置相關聯。 應用程式直接受益於這種關聯,提升了可靠性與易用性。 我們建議服務物件盡可能支援即插即用功能。
即插即用行為
一旦服務物件與 POS 裝置的硬體 ID 關聯,POS for .NET 會使用 Windows 即插即用管理器來判斷連接到電腦的 POS 裝置。 應用程式或服務物件不需要額外程式碼。
當應用程式呼叫 PosExplorer.GetDevices 方法時, PosExplorer 會找到與每個即插即用服務物件相關聯的裝置,然後查詢 Windows 即插即用管理器以判斷該裝置的狀態。 若裝置無法使用,則不會被加入從 PosExplorer.GetDevice 回傳至應用程式的裝置清單中。
PosExplorer 服務物件過濾
當應用程式呼叫 PosExplorer.GetDevices 時,PosExplorer 能有效篩選即插即用服務物件清單。 過濾過程如下:
- 搜尋指定 POS for .NET 目錄中的所有組件。
- 如果該組裝檔沒有標示 PosAssembly 全域屬性,則丟棄它。
- 以
ServiceObject屬性標記的類別進行搜尋。 對於每個此類類別:- 尋找與此類別相關的硬體 ID,無論是在
HardwareId屬性中還是 即插即用 XML 配置 檔中。 若無硬體 ID,則將服務物件留在 PosExplorer 清單中。 - 如果有硬體 ID,則可查詢 Windows 以取得該裝置的狀態。 如果裝置已連接到電腦,則會將其留在 PosExplorer 清單中。
- 如果裝置未連接到電腦,則從 PosExplorer 清單中移除。
- 尋找與此類別相關的硬體 ID,無論是在
Example
以下程式碼範例展示了處理即插即用事件的簡單方法。 PosExplorer 產生的資訊用來實例化正確的裝置,此處為磁條讀取器(MSR)。
// Connect the Plug and Play events to detect the removal or
// connection of a new device.
explorer.DeviceAddedEvent += new
DeviceChangedEventHandler(explorer_DeviceAddedEvent);
explorer.DeviceRemovedEvent += new
DeviceChangedEventHandler(explorer_DeviceRemovedEvent);
// This event handler extends Plug and Play functionality to the MSR
// device type. A message is printed to the console if the connection
// is successful.
void explorer_DeviceAddedEvent(object sender, DeviceChangedEventArgs e)
{
// Checks if the newly added device is an MSR.
if (e.Device.Type == DeviceType.Msr)
{
// Checks if an MSR instance has already been created and,
// if not,creates one. If a new MSR instance is created, its
// name is recorded in a string and written to the console.
// Once the printing is finished, the MSR is closed.
if (msr == null)
{
CreateMsr(e.Device);
strMsrConfig = e.Device.ServiceObjectName;
Console.WriteLine(strMsrConfig);
// It is important that applications close all open
// Service Objects before terminating.
msr.Close();
}
}
}