adding Transparent Form in Panel

Ashu seh 60 Reputation points
2023-11-21T13:08:13.5766667+00:00

Hi ,

I had started a new project in which i am opening c# forms and closing many times . I searched and found many suggestion but my problem is somewhat different . I have a single page in my project . and had to provide some space in it to show the closing and opening of forms . So I decided to introduce a panel in it and used to show forms in there . all is going well untill a problem came . i had to do the below
https://stackoverflow.com/questions/34947504/how-to-show-a-pop-up-message-with-dark-background?noredirect=1&lq=1

(add a dark blackground form before opening a form which have something to be in focus . )

before moving forward I must tell you why i choose panel . because by using panel , the form would stick inside the bounds of panel so that whenever i panel moves so as the form inside it . but ...

now the worst problem came when i came to know that transaprent/opaque forms cannot be added to the panel . It just shattered every logic of my project as i was stuck and found absolutely no solution whatso ever in any form .

Now here in this forum , i found some comments that say that for this opening and closing of forms ,a separte technique has to be used like creating a user control but i found no reference of this (creation of user control ) in their comments . They didn't say why and how the problem would be solved . So i am requesting any expert here to please help by creating a basic model for this .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. KOZ6.0 6,735 Reputation points
    2023-11-22T05:06:04.41+00:00

    If the OS is Windows 8 or higher, you can make the child window a layered window. To do this, add an application manifest and enable Windows 8.

    enter image description here

    <!-- Windows 8 -->
    <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
    

    Create a class that inherits UserControl.

    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    public class LayerdUserControl : UserControl
    {
        private Color _TransparencyKey = Color.Empty;
        private double _Opacity = 1.0f;
    
        protected override void OnHandleCreated(EventArgs e) {
            base.OnHandleCreated(e);
            var dwStyle = GetWindowLong(Handle, GWL_EXSTYLE);
            dwStyle |= WS_EX_LAYERED;
            SetWindowLong(Handle, GWL_EXSTYLE, dwStyle);
            UpdateLayered();
            BeginInvoke(new MethodInvoker(InvalidateChildren));
        }
    
        protected override void OnInvalidated(InvalidateEventArgs e) {
            base.OnInvalidated(e);
            InvalidateChildren();
        }
    
        protected virtual void InvalidateChildren() {
            if (HasChildren) {
                foreach (Control con in Controls) {
                    con.Invalidate(true);
                }
            }
        }
    
        private void UpdateLayered() {
            if (DesignMode || !IsHandleCreated) {
                return;
            }
    
            Color transparencyKey = TransparencyKey;
            byte opacityAsByte = (byte)(Opacity * 255.0f);
            bool result;
            if (transparencyKey.IsEmpty) {
                result = SetLayeredWindowAttributes(Handle, 0, opacityAsByte, LWA_ALPHA);
            } else if (opacityAsByte == 255) {
                result = SetLayeredWindowAttributes(Handle, ColorTranslator.ToWin32(transparencyKey), 0, LWA_COLORKEY);
            } else {
                result = SetLayeredWindowAttributes(Handle, ColorTranslator.ToWin32(transparencyKey),
                                                            opacityAsByte, LWA_ALPHA | LWA_COLORKEY);
            }
            if (!result) {
                throw new Win32Exception();
            }
        }
    
        [Category("LayerdWindow")]
        public virtual Color TransparencyKey {
            get {
                return _TransparencyKey;
            }
            set {
                if (_TransparencyKey != value) {
                    _TransparencyKey = value;
                    UpdateLayered();
                }
            }
        }
    
        protected virtual void ResetTransparencyKey() {
            TransparencyKey = Color.Empty;
        }
    
        protected virtual bool ShouldSerializeTransparencyKey() {
            return !_TransparencyKey.IsEmpty;
        }
    
        [Category("LayerdWindow")]
        [DefaultValue(1.0)]
        [TypeConverterAttribute(typeof(OpacityConverter))]
        public virtual double Opacity {
            get {
                return _Opacity;
            }
            set {
                if (_Opacity != value) {
                    _Opacity = value;
                    UpdateLayered();
                }
            }
        }
    
        private const int WS_EX_LAYERED = 0x80000;
        private const int GWL_EXSTYLE = -20;
        private const int LWA_COLORKEY = 1;
        private const int LWA_ALPHA = 2;
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SetLayeredWindowAttributes(IntPtr hwnd, int crKey, byte bAlpha, int dwFlags);
    }
    

    How To Use:

    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e) {
            var f = new LayerdUserControl();
            f.Text = string.Empty;
            f.Opacity = 0.5;
            f.BackColor = Color.Black;
            f.Dock = DockStyle.Fill;
            Controls.Add(f); 
            f.Show();
            f.BringToFront();
        }
    }
    

    enter image description here


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.