<a href="http://www.cjcraft.com/blog/2008/06/03/30DaysOfNETWindowsMobileApplicationsDay02BluetoothManager.aspx"></a>
Page Brooks為了省電,想一步完成Bluetooth開關的操作。
使用的技術有P/Invoke藍牙API, PictureBox, State and Notification Broker API.
看過我之前的文章會知道,在Windows Mobile下打開關閉Bluetooth,就是P/Invoke BthSetMode().
<a href="http://www.cnblogs.com/procoder/archive/2009/05/11/1454396.html">.NET Compact Framework下的Bluetooth開發 之 Windows Embedded Source Tools for Bluetooth</a>
<a href="http://www.cnblogs.com/procoder/archive/2009/05/14/1456243.html">.NET Compact Framework下的Bluetooth開發 之 32feet.NET</a>
<a href="http://www.cnblogs.com/procoder/archive/2009/05/15/1457114.html">.NET Compact Framework下的Bluetooth開發 之 Bluetooth Virtual Serial Port</a>
[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,而是自動關閉了,這是使用者友好性設計的表現。
由于Windows Mobile的Emulator不直接支援Bluetooth,是以源代碼需要在真實裝置上進行調試,為了友善,可以嘗試在Emulator調試。可以參考
<a href="http://www.cjcraft.com/blog/ct.ashx?id=0fdc8641-1d15-42a8-9908-64b20f5ac98d&url=http%3A%2F%2Fcid-0779b8ef58de4561.skydrive.live.com%2Fself.aspx%2FPublic%2FBluetoothManager.zip"></a>
參考文獻:
<a href="http://msdn.microsoft.com/en-us/library/aa455748.aspx" target="_blank">MSDN:State and Notifications Broker</a>
<a href="http://www.cnblogs.com/procoder/archive/2009/04/13/1434628.html">.NET Compact Framework, WinCE, Windows Mobile開發系列</a>
本文轉自Jake Lin部落格園部落格,原文連結:http://www.cnblogs.com/procoder/archive/2009/05/21/1471659.html,如需轉載請自行聯系原作者