1

我们有一个简单的用户控件,当我们在表单中使用它时可以正常工作,但是当我们尝试通过此方法将它托管到我们的 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);
}
4

2 回答 2

2

ToolStripControlHost 有一个奇怪的问题,它需要为其托管的控件设置 MinimumSize:

尝试添加这个:

suc.Size = new Size(30, 20);
suc.MinimumSize = suc.Size;
于 2012-10-10T15:54:25.567 回答
1

我有他同样的问题。我的解决方案是创建一个继承自 ToolStripControlHost 的新类并覆盖 ToolStripItem.OnPaint 方法,如下所示:

[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&view=category&layout=blog&id=3&limitstart=5

于 2012-10-16T19:44:58.293 回答