C#中半透明的窗体但不透明的控件

9
如何在C# Windows窗体应用程序中制作半透明表单
我尝试了TransparentKey,但它将其变为完全透明。我还尝试了Opacity,但它会影响整个带有控件的窗体。
我只想让表单部分是半透明的,而不是控件。
3个回答

9
您可以使用一种带有特定百分比的阴影画刷,例如:
    using System.Drawing.Drawing2D;

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        var hb = new HatchBrush(HatchStyle.Percent50, this.TransparencyKey);

        e.Graphics.FillRectangle(hb,this.DisplayRectangle);
    }

15
哦,天哪。结果太糟糕了。很抱歉,但这是实情。 - jay_t55

3

我发现Hatch Brush很丑陋,

改为:

protected override void OnPaintBackground(PaintEventArgs e) {
  var hb = new HatchBrush(HatchStyle.Percent80, this.TransparencyKey);
  e.Graphics.FillRectangle(hb, this.DisplayRectangle);
}

我使用了:

protected override void OnPaintBackground(PaintEventArgs e) {
  var sb = new SolidBrush(Color.FromArgb(100, 100, 100, 100));
  e.Graphics.FillRectangle(sb, this.DisplayRectangle);
}

完美,你的答案是唯一一个对我有帮助的。 - Héctor M.
这是针对WPF的吗?因为我在Windows Forms中找不到OnPaintBackground事件。 - Shilpa
是的,这是WPF而不是WinForms。为什么要使用WinForms,当你可以使用WPF呢? - user2342062

-1

有一个解决方案可以将半透明效果添加到一个控件(而不是窗体)中:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Apply opacity (0 to 255)
        panel1.BackColor = Color.FromArgb(25, panel1.BackColor);
    }

在 Visual Studio 中:(仅在执行期间激活的 alpha 版本)

enter image description here

在 Windows 7 上执行:

enter image description here

在一台旧的Windows 2003服务器上执行:

enter image description here

来源:https://dev59.com/E2855IYBdhLWcg3wPBpx#4464161


你的示例中表单不是半透明的,还是我漏看了什么? - user1027167
也许背景太过统一,不够清晰,但它确实可以使用 alpha 通道。如果你仔细观察,就会看到阴影 :) - 56ka
2
我已经测试过并得到了以下结果:button1是不透明的,panel1是半透明的,form1是不透明的。你看不到form后面的东西,但问题是关于一个半透明的form。所以我有同样的问题,但你的答案似乎不正确... - user1027167
我明白你的意思,你是对的。事实上,我回答了一个“控件”的问题,但问题是关于“窗体”的...我会更新。 - 56ka
5
我刚刚踩了这个问题,谁又点赞了它?这个回答应该被删除,因为它会引导人们走向错误的方向。 - user1027167
我尝试了这个,它抛出了一个ArgumentException异常,提示该控件不支持透明背景颜色。 - Adam L. S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接