0

在我的 WinForm 应用程序中,我需要对一些图像进行分层。但是,我无法获得透明控件来放置图像。我做了一些研究并提出了以下课程:

public class TransparentPicture : PictureBox
{
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;
            return cp;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // do nothing
    }

    protected override void OnMove(EventArgs e)
    {
        RecreateHandle();
    }

}

在我关闭 Visual Studios 并重新打开解决方案之前,这似乎工作正常。然后我的控件全部消失在设计器中。它们在我运行程序时显示,但我也需要它们在设计器中显示,我可以继续设计我的应用程序。

我知道这不是我需要做的所有事情,因为这些控件总是导致我的程序冻结几秒钟之类的东西。

所以我的问题是..有人知道我在哪里可以找到透明控件的代码,或者如何修复我拼凑在一起的代码吗?

4

1 回答 1

0

使TransparentPicture 成为常规PictureBox,直到IsTransparent 属性设置为true。

在设计时将该属性设置为 false,并在 FormLoad 事件中设置为 true(仅在您实际运行应用程序时才会发生)。

这样,在设计时,它们将表现得像普通的图片框,但是当您运行应用程序时,它们将变得透明。

public class TransparentPicture : PictureBox
{
    public bool IsTransparent { get; set; }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;

            if (this.IsTransparent)
            {
                cp.ExStyle |= 0x20;
            }

            return cp;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        if (!this.IsTransparent)
        {
            base.OnPaintBackground(e);
        }
    }

    protected override void OnMove(EventArgs e)
    {
        if (this.IsTransparent)
        {
            RecreateHandle();
        }
        else
        {
            base.OnMove(e);
        }
    }
}

然后,在您的 FormLoad 事件中,您应该执行以下操作:

for (var i = 0; i < this.Controls.Count; i++)
{
    var tp = this.Controls[i] as TransparentPicture;

    if (tp != null)
    {
        tp.IsTransparent = true;
    }
}

或者,如果您只有几个:

tp1.IsTransparent = tp2.IsTransparent = tp3.IsTransparent = true;
于 2012-04-22T14:52:28.397 回答