在.net中,工具栏和imagelist紧密结合,一般是在visualstudio中,一个一个添加imagelist的图标,再将其添加到toolbar中,此方法简单实用,但这样操作不便于实现换肤等扩展操作,如果使用图像条将得到更好的效果。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace Tool
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
ImageList imageLst=new ImageList(); //新建一个imagelist实例
imageLst.ImageSize=new Size(32,32); //定义其图标大小为32*32
imageLst.ColorDepth=ColorDepth.Depth32Bit; //定义色深
Image strip=Image.FromFile(@"skin/Toolbar.png"); //在项目文件夹bin/debug中新建skin文件夹
imageLst.Images.AddStrip(strip); //并将所需的图像条放入skin。使用AddStrip方法,按照上面定义的图标大小切割Toolbar.png。
ToolBar toolBar=new ToolBar(); //新建toolbar实例
toolBar.Parent=this;
toolBar.ImageList=imageLst;
for(int i=0;i<10;i++) //添加10个按钮
{
ToolBarButton toolBtn=new ToolBarButton();
toolBtn.ImageIndex=i;
toolBar.Buttons.Add(toolBtn);
}
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(712, 306);
this.Name = "Form1";
this.Text = "Form1";
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
注:在实例化imagelist时,可以添加其透明色属性,由于我使用的是透明的png图像,所以忽略。在添加按钮
事件时,toolbar本身没有为每个button设置事件委托,所以可以用imagelist的索引进行操作,参考msdn可解
决此问题。