在C# WinForms应用程序中,ToolStripButton
控件是ToolStrip
控件的一个重要组成部分,用于创建工具栏上的按钮。下面实战演示如何在WinForms项目中使用ToolStripButton:
步骤 1: 创建一个新的WinForms项目
打开Visual Studio并创建一个新的Windows Forms App (.NET Framework)项目。
步骤 2: 添加ToolStrip控件
在设计器中拖放一个ToolStrip
控件到窗体上。这将在窗体的顶部创建一个空白的工具栏。
步骤 3: 添加ToolStripButton
在ToolStrip
控件上,你可以直接添加ToolStripButton
控件。只需从工具箱中拖动ToolStripButton
到工具栏上即可。你也可以在属性窗口中编辑Items
集合来添加ToolStripButton
实例。
步骤 4: 编程处理ToolStripButton的Click事件
对于每个ToolStripButton
,你可能想要添加一些事件处理程序来响应用户的点击操作。例如:
Csharp
1private void toolStripButton1_Click(object sender, EventArgs e)
2{
3 MessageBox.Show("toolStripButton1 was clicked!");
4}
完整示例代码
下面是一个完整的示例,展示如何在WinForms应用程序中使用ToolStripButton
:
Csharp
1using System;
2using System.Windows.Forms;
3
4namespace ToolStripButtonDemo
5{
6 public partial class MainForm : Form
7 {
8 public MainForm()
9 {
10 InitializeComponent();
11 InitializeToolStrip();
12 }
13
14 private void InitializeToolStrip()
15 {
16 // 创建 ToolStripButton 实例
17 ToolStripButton buttonNew = new ToolStripButton("New");
18 ToolStripButton buttonSave = new ToolStripButton("Save");
19 ToolStripButton buttonExit = new ToolStripButton("Exit");
20
21 // 设置按钮的 Image 和 Click 事件处理器
22 buttonNew.Image = Properties.Resources.new_icon;
23 buttonNew.Click += ButtonNew_Click;
24
25 buttonSave.Image = Properties.Resources.save_icon;
26 buttonSave.Click += ButtonSave_Click;
27
28 buttonExit.Image = Properties.Resources.exit_icon;
29 buttonExit.Click += ButtonExit_Click;
30
31 // 添加按钮到 ToolStrip
32 toolStrip.Items.Add(buttonNew);
33 toolStrip.Items.Add(buttonSave);
34 toolStrip.Items.Add(new ToolStripSeparator());
35 toolStrip.Items.Add(buttonExit);
36 }
37
38 private void ButtonNew_Click(object sender, EventArgs e)
39 {
40 MessageBox.Show("New document created.");
41 }
42
43 private void ButtonSave_Click(object sender, EventArgs e)
44 {
45 MessageBox.Show("Document saved.");
46 }
47
48 private void ButtonExit_Click(object sender, EventArgs e)
49 {
50 this.Close();
51 }
52 }
53}
这个例子中,我们首先创建了三个ToolStripButton
实例,分别为“New”、“Save”和“Exit”。然后,我们给每个按钮分配了一个图标,并设置了点击事件处理器。最后,我们将这些按钮添加到了工具栏上,并添加了一个分隔符来区分功能组。
更多的应用,你可以根据自己的需求修改代码,添加更多的功能和样式。