2011-06-24 46 views
0

我想在我的应用程序中使用完全透明的模态窗体,并且能够用部分透明的图像填充它;为此,我曾经从表单中删除所有可见的元素,并获得了下面的代码。C# - 窗口上的透明模态窗体

class WinScreenshotWindow : Form 
{ 
    public WinScreenshotWindow() 
    { 
     // Create from without erasing background with a color 
     // Going not to use transparent form instead, it will produce context menu bugs in textboxes for child form 
     this.SuspendLayout(); 
     this.MaximizeBox = false; 
     this.MinimizeBox = false; 
     this.ShowIcon = false; 
     this.ShowInTaskbar = false; 
     this.FormBorderStyle = FormBorderStyle.None; 
     this.StartPosition = FormStartPosition.Manual; 
     this.ControlBox = false; 
     this.Visible = false; 
     this.Size = new Size(100, 100); 
     this.Location = new Point(200, 200); 
     this.ResumeLayout(); 
    } 

    protected override void OnPaintBackground(PaintEventArgs e) 
    { 
     // Erase Background Windows message: 
    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     Rectangle clientRect = e.ClipRectangle; 
     e.Graphics.FillRectangle(Brushes.Transparent, clientRect); 
    } 
} 

    static void Main() 
    { 
     Form form = new Form(); 
     form.Size = new Size(400, 400); 
     form.Show(); 

     var ww = new WinScreenshotWindow(); 
     ww.ShowDialog(form); 
    } 

但结果是一些奇怪的事情:

Bug

当我在OnPaint()方法移除填充,它是不可见的。 问题是 - 为什么会发生这种情况?如果背景是透明的,为什么它以这种方式显示窗体?在这种情况下可以做些什么?

任何帮助表示赞赏。

+0

不绘画背景给你随机像素。使用TransparencyKey。 –

回答

1

用红色背景打开无边界窗体并设置TransparencyKey = red?不是更容易吗?

+0

这工作很酷,但我需要使用一种颜色作为透明度键。 TransparencyKey = Color.Transparency不起作用。如果我有透明度键的颜色的图像怎么办? – Zelzer

+0

@Zelzer如果颜色与您的密钥相匹配,您可能会冒险在图像中插入空洞。这种建议是尝试选择一种很少使用的颜色,如柠檬绿或粉红色(我猜根据图像的不同,很少见)。 – LarsTech