如果您的 Windows Form 具備包含工具列按鈕的 ToolBar 控制項,則會想要知道使用者所按的按鈕。
在 ToolBar 控制項的 ButtonClick 事件上,您可以評估 ToolBarButtonClickEventArgs 類別的 Button 屬性。 在下列範例中,會顯示訊息方塊,指出所按的按鈕。 如需詳細資訊,請參閱 MessageBox。
下列範例假設已將 ToolBar 控制項新增至 Windows Form。
處理工具列上的 Click 事件
在程序中,將工具列按鈕新增至 ToolBar 控制項。
Public Sub ToolBarConfig() ' Instantiate the toolbar buttons, set their Text properties ' and add them to the ToolBar control. ToolBar1.Buttons.Add(New ToolBarButton("One")) ToolBar1.Buttons.Add(New ToolBarButton("Two")) ToolBar1.Buttons.Add(New ToolBarButton("Three")) ' Add the event handler delegate. AddHandler ToolBar1.ButtonClick, AddressOf Me.ToolBar1_ButtonClick End Subpublic void ToolBarConfig() { toolBar1.Buttons.Add(new ToolBarButton("One")); toolBar1.Buttons.Add(new ToolBarButton("Two")); toolBar1.Buttons.Add(new ToolBarButton("Three")); toolBar1.ButtonClick += new ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); }public: void ToolBarConfig() { toolBar1->Buttons->Add(gcnew ToolBarButton("One")); toolBar1->Buttons->Add(gcnew ToolBarButton("Two")); toolBar1->Buttons->Add(gcnew ToolBarButton("Three")); toolBar1->ButtonClick += gcnew ToolBarButtonClickEventHandler(this, &Form1::toolBar1_ButtonClick); }針對 ToolBar 控制項的 ButtonClick 事件新增事件處理常式。 使用 case switching 陳述式和 ToolBarButtonClickEventArgs 類別來判斷已點擊的工具列按鈕。 有鑑於此,會顯示適當的訊息方塊。
備註
在此範例中,訊息方塊僅作為預留位置使用。 依需要新增要在按一下工具列按鈕時執行的其他程式碼。
Protected Sub ToolBar1_ButtonClick(ByVal sender As Object, _ ByVal e As ToolBarButtonClickEventArgs) ' Evaluate the Button property of the ToolBarButtonClickEventArgs ' to determine which button was clicked. Select Case ToolBar1.Buttons.IndexOf(e.Button) Case 0 MessageBox.Show("First toolbar button clicked") Case 1 MessageBox.Show("Second toolbar button clicked") Case 2 MessageBox.Show("Third toolbar button clicked") End Select End Subprotected void toolBar1_ButtonClick(object sender, ToolBarButtonClickEventArgs e) { // Evaluate the Button property of the ToolBarButtonClickEventArgs // to determine which button was clicked. switch (toolBar1.Buttons.IndexOf(e.Button)) { case 0 : MessageBox.Show("First toolbar button clicked"); break; case 1 : MessageBox.Show("Second toolbar button clicked"); break; case 2 : MessageBox.Show("Third toolbar button clicked"); break; } }protected: void toolBar1_ButtonClick(System::Object ^ sender, ToolBarButtonClickEventArgs ^ e) { // Evaluate the Button property of the ToolBarButtonClickEventArgs // to determine which button was clicked. switch (toolBar1->Buttons->IndexOf(e->Button)) { case 0 : MessageBox::Show("First toolbar button clicked"); break; case 1 : MessageBox::Show("Second toolbar button clicked"); break; case 2 : MessageBox::Show("Third toolbar button clicked"); break; } }