HOW TO:使用 HardwareButton 元件
更新:2007 年 11 月
您可以設定 Pocket PC 上的硬體按鈕以啟動 Form。在這個範例中,會以第一和第四個硬體按鈕啟動應用程式,並在狀態列中指示按下了哪一個按鈕。
若要設定硬體按鈕以啟動表單
建立 Pocket PC Windows 應用程式。
建立 HardwareButton 的執行個體。
將 AssociatedControl 屬性設定為表單。
將 HardwareKey 屬性設定為 HardwareKeys 列舉型別所定義的應用程式索引鍵。
重複執行步驟 2 到 4,設定要使用的其他硬體按鈕。
當按下並釋放硬體按鈕時,表單會同時收到 KeyDown 和 KeyUp 兩個事件。您可以使用其中任何一個事件判斷是否按下了某個硬體按鈕。
範例
在這個範例中,會設定第一個和第四個硬體按鈕啟動表單。如需示範,請執行下列步驟:
執行應用程式。
開啟裝置上的另一個應用程式。
按下硬體按鈕 1 或 4,啟動此應用程式的表單。狀態列會指示按下了哪一個硬體按鈕。
Private Sub ConfigHWButton()
' Set KeyPreview to true so that the form
' will receive key events before they
' are passed to the control that has focus.
Me.KeyPreview = True
hwb1 = New HardwareButton()
hwb4 = New HardwareButton()
' Set the AssociatedControl property
' to the current form and configure the
' first and fourth buttons to activate the form.
Try
hwb1.AssociatedControl = Me
hwb4.AssociatedControl = Me
hwb1.HardwareKey = HardwareKeys.ApplicationKey1
hwb4.HardwareKey = HardwareKeys.ApplicationKey4
Catch exc As Exception
MessageBox.Show(exc.Message & " Check if the hardware button is " & _
"physically available on this device.")
End Try
End Sub
Private Overloads Sub OnKeyUp(sender As Object, e As KeyEventArgs) _
Handles MyBase.KeyUp
' When a hardware button is pressed and released,
' this form receives the KeyUp event. The OnKeyUp
' method is used to determine which hardware
' button was pressed, because the event data
' specifies a member of the HardwareKeys enumeration.
Select Case CType(e.KeyCode, HardwareKeys)
Case HardwareKeys.ApplicationKey1
statusBar1.Text = "Button 1 pressed."
Case HardwareKeys.ApplicationKey4
statusBar1.Text = "Button 4 pressed."
Case Else
End Select
End Sub
// Configure hardware buttons
// 1 and 4 to activate the current form.
private void HBConfig()
{
try
{
hwb1 = new HardwareButton();
hwb4 = new HardwareButton();
hwb1.AssociatedControl = this;
hwb4.AssociatedControl = this;
hwb1.HardwareKey = HardwareKeys.ApplicationKey1;
hwb4.HardwareKey = HardwareKeys.ApplicationKey4;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message + " Check if the hardware " +
"button is physically available on this device.");
}
}
// When a hardware button is pressed and released,
// this form receives the KeyUp event. The OnKeyUp
// method is used to determine which hardware
// button was pressed, because the event data
// specifies a member of the HardwareKeys enumeration.
private void OnKeyUp(object sender, KeyEventArgs e)
{
switch ((HardwareKeys)e.KeyCode)
{
case HardwareKeys.ApplicationKey1:
statusBar1.Text = "Button 1 pressed.";
break;
case HardwareKeys.ApplicationKey4:
statusBar1.Text = "Button 4 pressed.";
break;
default:
break;
}
}
編譯程式碼
這個範例需要參考下列命名空間: