在具有一些控件的窗体上绘制半透明叠加图像

MLS*_*MLS 9 c# overlay transparent

在窗体上绘制半透明叠加图像,其中包含一些控件,使其所有子控件都可见,但不能单击它们.它应该像我们通过一些半透明的黑色镜子看到一些东西.

我尝试过使用透明控件.这是对该控件的Panel控件和绘图图像的子类,但是所有控件都是完全可见的.

Han*_*ant 27

这将需要您在现有表单上显示的另一个表单.其Opacity属性可以创建预期的效果.在项目中添加一个新类并粘贴下面显示的代码.调用Close()方法再次删除效果.

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class Plexiglass : Form {
    public Plexiglass(Form tocover) {
        this.BackColor = Color.DarkGray;
        this.Opacity = 0.30;      // Tweak as desired
        this.FormBorderStyle = FormBorderStyle.None;
        this.ControlBox = false;
        this.ShowInTaskbar = false;
        this.StartPosition = FormStartPosition.Manual;
        this.AutoScaleMode = AutoScaleMode.None;
        this.Location = tocover.PointToScreen(Point.Empty);
        this.ClientSize = tocover.ClientSize;
        tocover.LocationChanged += Cover_LocationChanged;
        tocover.ClientSizeChanged += Cover_ClientSizeChanged;
        this.Show(tocover);
        tocover.Focus();
        // Disable Aero transitions, the plexiglass gets too visible
        if (Environment.OSVersion.Version.Major >= 6) {
            int value = 1;
            DwmSetWindowAttribute(tocover.Handle, DWMWA_TRANSITIONS_FORCEDISABLED, ref value, 4);
        }
    }
    private void Cover_LocationChanged(object sender, EventArgs e) {
        // Ensure the plexiglass follows the owner
        this.Location = this.Owner.PointToScreen(Point.Empty);
    }
    private void Cover_ClientSizeChanged(object sender, EventArgs e) {
        // Ensure the plexiglass keeps the owner covered
        this.ClientSize = this.Owner.ClientSize;
    }
    protected override void OnFormClosing(FormClosingEventArgs e) {
        // Restore owner
        this.Owner.LocationChanged -= Cover_LocationChanged;
        this.Owner.ClientSizeChanged -= Cover_ClientSizeChanged;
        if (!this.Owner.IsDisposed && Environment.OSVersion.Version.Major >= 6) {
            int value = 1;
            DwmSetWindowAttribute(this.Owner.Handle, DWMWA_TRANSITIONS_FORCEDISABLED, ref value, 4);
        }
        base.OnFormClosing(e);
    }
    protected override void OnActivated(EventArgs e) {
        // Always keep the owner activated instead
        this.BeginInvoke(new Action(() => this.Owner.Activate()));
    }
    private const int DWMWA_TRANSITIONS_FORCEDISABLED = 3;
    [DllImport("dwmapi.dll")]
    private static extern int DwmSetWindowAttribute(IntPtr hWnd, int attr, ref int value, int attrLen);
}
Run Code Online (Sandbox Code Playgroud)


Ron*_*lic 3

创建一个分层窗口,该窗口保留在主表单的顶部并与其位置同步。您可以使用 32 位 RGBA 图像更改分层窗口的 Alpha,以获得所需的效果。

这里有一篇不错的代码项目文章向您展示了如何做到这一点。