Search code examples
c#winformsgdi+gdi

DrawParentBackground / DrawThemeParentBackground on a top level form


Consider the following example. This was done by setting the TransparencyKey property:

public Form()
{
    this.InitializeComponent();
    this.BackColor = Color.Fuscia;
    this.TransparencyKey = this.BackColor;
}

Example form

What I actually want to be able to do is similar to the behavior of the DrawThemeParentBackground function (conveniently wrapped up in .NET as DrawParentBackground), however this does not seem to work for top level forms (only controls).

I have tried to use the TransparencyKey behavior along with overriding the OnPaint method:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(128, 255, 0, 0)), this.ClientRectangle);
}

Result:

Example

Question:

How can I draw the content underneath the ClientRectangle of a top level form?


Solution

  • Is this the effect you want?

    enter image description here

    If so, you can use two different forms. You do the drawing in the second one.

    public partial class Form1 : Form
    {
        private Form2 form2;
    
        public Form1()
        {
            InitializeComponent();
            this.BackColor = Color.White;
            this.TransparencyKey = Color.White;
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(200, 200);
            form2 = new Form2();
            form2.StartPosition = this.StartPosition;
            form2.Location = this.Location;
            form2.Show();
    
            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
            this.LocationChanged += new EventHandler(Form1_LocationChanged);
            this.SizeChanged += new EventHandler(Form1_SizeChanged);
        }
    
        void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            form2.Close();
        }
    
        void Form1_LocationChanged(object sender, EventArgs e)
        {
            form2.Location = this.Location;
        }
    
        void Form1_SizeChanged(object sender, EventArgs e)
        {
            form2.Size = this.Size;
        }
    }
    

    and

     public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            ShowInTaskbar = false;
            this.Opacity = 0.8;
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(255, 0, 0)), this.ClientRectangle);
        }
    }