如何:为控件提供工具箱位图

更新:2007 年 11 月

如果希望在“工具箱”中为控件显示特殊图标,可以通过使用 ToolboxBitmapAttribute 来指定一个特定的图像。此类是一种属性,这是一种可以附加到其他类上的特殊类。有关属性的更多信息,对于 Visual Basic 请参见 Visual Basic 中的属性概述,对于 Visual C# 请参见 属性(C# 编程指南)

通过使用 ToolboxBitmapAttribute,可以指定一个字符串来指示一个 16 x 16 像素位图的路径和文件名。此位图在添加到“工具箱”后显示在对应的控件旁边。还可以指定 Type,在这种情况下会加载与该类型关联的位图。如果您同时指定 Type 和字符串,则控件在包含由 Type 参数指定的类型的程序集中搜索其名称由 String 参数指定的图像资源。

指定控件的工具箱位图

  1. ToolboxBitmapAttribute 添加至控件的类声明中,对于 Visual Basic 应置于 Class 关键字之前,对于 Visual C# 则应置于类声明之前。

    ' Specifies the bitmap associated with the Button type.
    <ToolboxBitmap(GetType(Button))> Class MyControl1
    ' Specifies a bitmap file.
    End Class
    <ToolboxBitmap("C:\Documents and Settings\Joe\MyPics\myImage.bmp")> _
       Class MyControl2
    End Class
    ' Specifies a type that indicates the assembly to search, and the name 
    ' of an image resource to look for.
    <ToolboxBitmap(GetType(MyControl), "MyControlBitmap")> Class MyControl
    End Class
    
    // Specifies the bitmap associated with the Button type.
    [ToolboxBitmap(typeof(Button))]
    class MyControl1 : UserControl
    {
    }
    // Specifies a bitmap file.
    [ToolboxBitmap(@"C:\Documents and Settings\Joe\MyPics\myImage.bmp")]
    class MyControl2 : UserControl
    {
    }
    // Specifies a type that indicates the assembly to search, and the name 
    // of an image resource to look for.
    [ToolboxBitmap(typeof(MyControl), "MyControlBitmap")]
    class MyControl : UserControl
    {
    }
    
    // Specifies the bitmap associated with the Button type.
    /** @attribute ToolboxBitmap(Button.class)  */
    class MyControl1 extends UserControl
    {
    }
    // Specifies a bitmap file.
    /** @attribute ToolboxBitmap("C:\\Documents and Settings\\Joe\\MyPics\\myImage.bmp")*/
    class MyControl2 extends UserControl
    {
    }
    // Specifies a type that indicates the assembly to search, and the name 
    // of an image resource to look for.
    /* @attribute ToolboxBitmap(MyControl.class, "MyControlBitmap") */
    class MyControl extends UserControl
    {
    }
    
  2. 重新生成项目。

    说明:

    对于自动生成的控件和组件,位图将不出现在工具箱中。若要查看位图,请使用“选择工具箱项”对话框重新加载控件。有关更多信息,请参见演练:使用自定义组件自动填充工具箱

请参见

任务

演练:使用自定义组件自动填充工具箱

参考

属性(C# 编程指南)

ToolboxBitmapAttribute

其他资源

设计时开发 Windows 窗体控件

Visual Basic 属性