【问题标题】:True Transparent Picturebox in VS2010VS2010中的真透明图片框
【发布时间】:2012-05-03 09:03:18
【问题描述】:

在我的 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 并重新打开解决方案。然后我的控件全部消失在设计器中。它们在我运行程序时显示,但我还需要它们在设计器中显示,以便我可以继续设计我的应用程序。

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

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

【问题讨论】:

  • WinForms 并不真正支持真正的透明度。使用 WPF。
  • 您可以通过代码检查您是否处于设计模式,如果是,则不运行|= 0x20,运行base.OnPaintBackground等。
  • PictureBox 已经支持透明度,无需任何特殊技巧。只需将 BackColor 设置为 Color.Transparent。查看上一个链接以获取屏幕截图。

标签: c# winforms visual-studio transparency picturebox


【解决方案1】:

使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;

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多