在使用.net toolStrip控件的时候, toolStrip里面的item宽度超过本身宽度时,会出现一个溢出按钮:OverflowButton,这个按钮是控件的一个属性,其实也是继承自ToolStripDropDownItem,默认样式如下图:
如何才能替换成像chrome书签栏一样的向右小箭头呢?
本以为直接使用toolStrip.OverflowButton.BackgroundImage=Image.FromFile("OverflowArrowVertical.png")就能解决,可是这样好像没有任何效果。
toolStrip的Renderer属性,能够让用户使用自定义的外观,只需要继承ToolStripRenderer类,重写其中的方法就能定义自己的样式,toolStrip的RenderMode是一个枚举值:
public enum ToolStripRenderMode
{
// 摘要:
// Indicates that the System.Windows.Forms.ToolStrip.RenderMode is not determined
// by the System.Windows.Forms.ToolStripManager or the use of a System.Windows.Forms.ToolStripRenderer
// other than System.Windows.Forms.ToolStripProfessionalRenderer, System.Windows.Forms.ToolStripSystemRenderer
[Browsable(false)]
Custom = ,
//
// 摘要:
// Indicates the use of a System.Windows.Forms.ToolStripSystemRenderer to paint.
System = ,
//
// 摘要:
// Indicates the use of a System.Windows.Forms.ToolStripProfessionalRenderer
// to paint.
Professional = ,
//
// 摘要:
// Indicates that the System.Windows.Forms.ToolStripManager.RenderMode or System.Windows.Forms.ToolStripManager.Renderer
// determines the painting style.
ManagerRenderMode = ,
}
可以看到,.net本身提供了4种样式,要实现图标替换,只需要继承任意一个样式并重写OnRenderOverflowButtonBackground方法即可。代码如下:
public class DrawOverflowButtonRenderer : System.Windows.Forms.ToolStripProfessionalRenderer
{
Image ofArrowVertical;
public DrawOverflowButtonRenderer(Image pic)
{
ofArrowVertical = pic;
} protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
if (e.ToolStrip.OverflowButton.Enabled)
{
if (e.ToolStrip.OverflowButton.Pressed)
{
LinearGradientBrush lgb = new LinearGradientBrush(e.ToolStrip.OverflowButton.Bounds, ofPressedColor1, ofPressedColor2, ofPressedAngle);
e.Graphics.FillRectangle(lgb, e.Graphics.ClipBounds);
lgb.Dispose(); }
else if (e.ToolStrip.OverflowButton.Selected)
{
LinearGradientBrush lgb = new LinearGradientBrush(e.ToolStrip.OverflowButton.Bounds, ofHighlightColor1, ofHighlightColor2, ofHighlightAngle);
e.Graphics.FillRectangle(lgb, e.Graphics.ClipBounds);
lgb.Dispose();
}
}
e.Graphics.DrawImage(ofArrowVertical, new Rectangle(, e.ToolStrip.OverflowButton.Height - ofArrowVertical.Height, e.ToolStrip.OverflowButton.Bounds.Width, e.ToolStrip.OverflowButton.Bounds.Height));
}
}
调用:this.toolStrip1.Renderer = new DrawOverflowButtonRenderer(Image.FromFile("OverflowArrowVertical.png"))便能替换图标了,最终效果:
这个问题纠结了好久,各种谷歌百度,论坛提问都没人解决,平时伸手党惯了,这个控件不行就用其他控件替代,最终还是用英文在google搜了一把,在codeproject上看了老外的一个讨论后得到启示才解决这个问题。感谢万能的谷歌!