原文見 Day 02: Bluetooth
Manager
需求
Page Brooks為了省電,想一步完成Bluetooth開關的操作。
實現
使用的技術有P/Invoke藍芽API, PictureBox, State and Notification Broker API.
看過我之前的文章會知道,在Windows Mobile下開啟關閉Bluetooth,就是P/Invoke BthSetMode().
.NET
Compact Framework下的Bluetooth開發 之 Windows Embedded Source Tools for Bluetooth
.NET
Compact Framework下的Bluetooth開發 之 32feet.NET
.NET
Compact Framework下的Bluetooth開發 之 Bluetooth Virtual Serial Port
[DllImport("BthUtil.dll")]
private static extern int BthGetMode(out RadioMode dwMode);
[DllImport("BthUtil.dll")]
private static extern int BthSetMode(RadioMode dwMode);
狀態變更功能,如果外部程式變更了Bluetooth的狀態,當前程式需要被通知並處理變更。
using Microsoft.WindowsMobile.Status;
SystemState bluetoothStatePowerOn = new SystemState(SystemProperty.BluetoothStatePowerOn);
bluetoothStatePowerOn.Changed += new ChangeEventHandler(bluetoothStatePowerOn_Changed);
void bluetoothStatePowerOn_Changed(object sender, ChangeEventArgs args)
{
UpdateScreen();
}
這裡使用了State and Notifications Broker API,需要引用Microsoft.WindowsMobile.Status庫。SystemState(SystemProperty.BluetoothStatePowerOn)指定了狀態監控的類型,產生Bluetooth開關的系統狀態物件,bluetoothStatePowerOn.Changed += new ChangeEventHandler(bluetoothStatePowerOn_Changed)訂閱Bluetooth開關係統狀態的變更訊息,並使用bluetoothStatePowerOn_Changed進行處理該訊息。
State and Notifications Brokerz API是一個很重要的API,這API可以監控註冊表的變化狀況。總所周知,在Windowns裡面註冊表就是保持系統資訊和應用程式資訊的小型資料庫。State and Notifications Brokerz API提供監控註冊表的功能,表示他能監控系統資訊以及應用程式資訊的變化。這些資訊包括網路攝影機狀態,ActiveSync,電源狀態,SMS,計劃任務,呼叫資訊,Bluetooth狀態,網路連結狀態,modem狀態等等。所以這API廣泛運用於系統資訊相關事件觸發的開發,參考連結見下面。
增加自動關閉程式功能。
private void timer_Tick(object sender, EventArgs e)
{
textBox.Text = string.Empty;
for (int i = 10; i > 0; i--)
{
textBox.Text += string.Format("Auto shutdown in {0} seconds" + Environment.NewLine, i);
Thread.Sleep(1000);
}
this.Close();
}
this.timer.Interval = 60000;
這個程式運行1分鐘後,自動關閉自己。在關閉前,有10秒鐘的倒數,目的使得使用者知道這個程式不是Crash,而是自動關閉了,這是方便使用性設計的表現。
Emulator下調試
由於Windows Mobile的Emulator不直接支援Bluetooth,所以原始碼需要在真實裝置上進行調試,為了方便,可以嘗試在Emulator調試。可以參考
施炯 同學的文章 在Windows Mobile模擬器上使用藍芽以及 Dmitry Klionsky的Bluetooth for Microsoft Device Emulator。
安裝程式: bluetoothManager.cab
原始碼: bluetoothManager.zip
參考文獻:
MSDN:State and
Notifications Broker
.NET Compact Framework, WinCE, Windows Mobile開發系列
Jake's Blog in 部落格園 -- 精簡開發 無線生活