2009-07-01 181 views
1

我正在打印到藍牙連接的打印機的移動應用程序(Tablet PC上的C#/ WPF)。現在我只是開始打印作業,如果打印機不存在,打印機子系統會向用戶報告錯誤。我沒有使用藍牙程序進行任何操作,只是使用PrintDialog()。檢測藍牙打印機的存在

我想修改此過程來首先檢測打印機 - 如果它不可用,那麼我將只存儲文檔而不打印。有沒有代碼的方式來檢測藍牙設備是否連接/活動/可用?

如果我在控制面板下的藍牙面板中查看設備,它似乎沒有任何反映設備是否可用的狀態,所以也許這是不可能的。

我假設打印機已經在Windows中設置和配置 - 我需要做的就是檢測它是否實際存在於給定的時間點。

回答

1

也許使用32feet.NET庫(其中我是維護者),並在提交作業前檢查打印機是否存在。您需要知道打印機的藍牙地址;能從系統中得到那個,或者你總是知道它。

MSFT藍牙堆棧上的發現總是返回範圍內的所有已知設備:-(但我們可以使用其他方式來檢測設備的存在/不存在,也許在其BeginGetServiceRecords表單中使用BluetoothDeviceInfo.GetServiceRecords。 (未測試/編譯):

bool IsPresent(BluetoothAddress addr) // address from config somehow 
{ 
    BluetoothDeviceInfo bdi = new BluetoothDeviceInfo(addr); 
    if (bdi.Connected) { 
     return true; 
    } 
    Guid arbitraryClass = BluetoothService.Headset; 
    AsyncResult<bool> ourAr = new AsyncResult<bool>(); // Jeffrey Richter's impl 
    IAsyncResult ar = bdi.BeginGetService(arbitraryClass, IsPresent_GsrCallback, ourAr); 
    bool signalled = ourAr.AsyncWaitHandle.WaitOne(Timeout); 
    if (!signalled) { 
     return false; // Taken too long, so not in range 
    } else { 
     return ourAr.Result; 
    } 
} 

void IsPresent_GsrCallback(IAsyncResult ar) 
{ 
    AsyncResult<bool> ourAr = (AsyncResult<bool>)ar.AsyncState; 
    const bool IsInRange = true; 
    const bool completedSyncFalse = true; 
    try { 
     bdi.EndGetServiceResult(ar); 
     ourAr.SetAsCompleted(IsInRange, completedSyncFalse); 
    } catch { 
     // If this returns quickly, then it is in range and 
     // if slowly then out of range but caller will have 
     // moved on by then... So set true in both cases... 
     // TODO check what error codes we get here. SocketException(10108) iirc 
     ourAr.SetAsCompleted(IsInrange, completedSyncFalse); 
    } 
}