This article aims to provide a solution for overlaying a semi-transparent image on a Windows Form containing other controls, ensuring that the controls remain visible but inaccessible.
To achieve this effect, we will use another form and place it on top of the existing form. The new form's Opacity
property controls the transparency level. Here is a custom class that can be added to your project:
<code class="language-csharp">using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; public class Plexiglass : Form { public Plexiglass(Form tocover) { // 自定义叠加窗体的外观和行为 this.BackColor = Color.DarkGray; this.Opacity = 0.30; 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(); // 禁用Aero过渡效果,以获得更流畅的效果 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) { this.Location = this.Owner.PointToScreen(Point.Empty); } private void Cover_ClientSizeChanged(object sender, EventArgs e) { this.ClientSize = this.Owner.ClientSize; } // 调整窗体行为,以确保目标窗体保持焦点 protected override void OnActivated(EventArgs e) { this.BeginInvoke(new Action(() => this.Owner.Activate())); } protected override void OnFormClosing(FormClosingEventArgs e) { 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); } // DWM API调用的常量 private const int DWMWA_TRANSITIONS_FORCEDISABLED = 3; [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr hWnd, int attr, ref int value, int attrLen); }</code>
To overlay an image, create an instance of the Plexiglass
class and pass the target form as a parameter when the form is displayed. This creates a semi-transparent overlay that covers the entire target form, allowing you to see existing controls but preventing interaction with them.
To remove the overlay, simply call the Plexiglass
method of the form instance. Close()
The above is the detailed content of How to Create a Semi-Transparent Overlay on a Windows Form Using C#?. For more information, please follow other related articles on the PHP Chinese website!