我们有一个简单的用户控件,当我们在表单中使用它时,它可以很好地工作,但当我们试图通过此方法将它托管到StatusStrip中时,永远不会调用OnPaint事件。MSDN文档指出这"应该"有效,但我们什么也没看到,并确认从未调用OnPaint事件。:
public partial class SimpleUserControl : UserControl
{
public SimpleUserControl( )
{
InitializeComponent( );
// Set the styles for drawing
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.DoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
true);
}
[System.ComponentModel.EditorBrowsableAttribute( )]
protected override void OnPaint( PaintEventArgs e )
{
Rectangle _rc = new Rectangle( 0, 0, this.Width, this.Height );
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.DrawArc( new Pen( Color.Red ), _rc, 180, 180 );
}
}
public Form1( )
{
InitializeComponent( );
SimpleUserControl suc = new SimpleUserControl( );
suc.Size = new Size( 30, 20 );
ToolStripControlHost tsch = new ToolStripControlHost( suc );
statusStrip1.Items.Add(tsch);
}
ToolStripControlHost有一个奇怪的怪癖,它需要为托管的控件设置MinimumSize:
尝试添加以下内容:
suc.Size = new Size(30, 20);
suc.MinimumSize = suc.Size;
我也遇到了同样的问题。我的解决方案是创建一个从ToolStripControlHost继承的新类,并覆盖ToolStripItem.OnPint方法,如下所示:
[System.ComponentModel.DesignerCategory("code")]
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All]
public class ToolStripSimpleUserControl : ToolStripControlHost
{
public ToolStripSimpleUserControl ()
: base(new SimpleUserControl())
{
}
public SimpleUserControl StripSimpleUserControl
{
get { return Control as SimpleUserControl; }
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// not thread safe!
if (e != null)
{
this.StripSimpleUserControl.Invalidate();
}
}
}
以公共形式1()
public Form1( )
{
InitializeComponent( );
ToolStripSimpleUserControl suc = new ToolStripSimpleUserControl( );
suc.StripSimpleUserControl.Size = new Size( 30, 20 );
statusStrip1.Items.Add(suc);
}
了解更多规则参观http://msdn.microsoft.com/en-us/library/9k5etstz.aspx
以及参观http://tonyfear.netau.net/index.php?option=com_content&视图=类别&layout=blog&id=3&limitstart=5