2012-04-22 101 views
0

在我的WinForm应用程序中,我需要分层显示一些图像。不过,我遇到了麻烦透明控制的图像放在我做了一些研究,并与下面的类上来。VS2010中的真实透明Picturebox

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(); 
    } 

} 

这似乎很好地工作,直到我关闭视觉工作室,并重新打开解。然后我的控制都消失在设计师身上。当我运行该程序时,它们会显示出来,但我需要他们向设计师展示我可以继续设计我的应用程序的位置。

我知道这不是我需要做的一切,因为这些控件总是让我的程序冻结几秒钟和东西。

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

+2

的WinForms真的不支持真正的透明。使用WPF。 – SLaks 2012-04-22 14:43:06

+0

您可以通过代码检查您是否在DesignMode中,并且不运行'| = 0x20',并运行'base.OnPaintBackground'等,如果是的话。 – SimpleVar 2012-04-22 14:46:15

+0

[C#Picturebox透明背景可能重复似乎不工作](http://stackoverflow.com/questions/5522337/c-sharp-picturebox-transparent-background-doesnt-seem-to-work) – 2012-04-22 15:43:56

回答

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;