Drawing on[/underneath!] Controls

Is it possible to draw a line as shown in the pic on a single form The line in the image is drawn on a second form which is transparent so form1 is visible.



Answer this question

Drawing on[/underneath!] Controls

  • Robs Pierre

    So why does my line control cover the listbox

    class Line : Control
    {
     Pen _Pen;

     Line()
     {
       this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
       this.BackColor = Color.Transparent; 

     }

     public void SetBounds(int Width)
     {
       _Pen = new Pen(new SolidBrush(Color.Red));
       _Pen.Width = Width;
       this.Location = new Point(0, 0);
       this.Height = Form1.ClientRectangle.Height;
       this.Width = Form1.ClientRectangle.Width;
       Invalidate();
     }

     protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
     {
       base.OnPaint(e);
       _Pen.DashCap = DashCap.Flat;
       _Pen.DashStyle = DashStyle.DashDotDot;
       _Pen.StartCap = LineCap.Flat;
       _Pen.EndCap = LineCap.ArrowAnchor;
       Graphics g = this.CreateGraphics;
       g.DrawBezier(_Pen, 20, 20, 500, 300, 550, 320, 510, 60);
     }
    }


  • hemo

    Try this instead:

    using System;
    using System.Drawing;
    using System.Windows.Forms;

    public class Line : Control {
    protected override CreateParams CreateParams {
    get {
    // Turn on the WS_EX_TRANSPARENT style
    CreateParams cp = base.CreateParams;
    cp.ExStyle |= 0x20;
    return cp;
    }
    }
    protected override void OnPaintBackground(PaintEventArgs pevent) {
    // Do *not* paint the background
    }
    protected override void OnPaint(PaintEventArgs e) {
    // Draw the line, just a demo here:
    e.Graphics.DrawLine(Pens.Black, 0, 0, this.Width, this.Height);
    base.OnPaint(e);
    }
    }

    If you animate the line in any way, you'll need to invalidate the control's Parent so the background is redrawn correctly.


  • Jafar Bhatti

    Thats a really working one thanks. BTW, could you please explain what it does in the CreateParams
  • Nodnarb501

    Can we then create the line as a control and set its background to transparent so the list box is visible through
  • Neil Ault

    Yes, that would work. Very similar to what you did with the transparent form.


  • Jesper Ekenberg

    Because this.BackColor = Color.Transparent; doesn't realy work as expected.
  • David Hanak

    As indicated, it turns on the WS_EX_TRANSPARENT window style. With this style set, Windows ensures that all windows "below" the window get painted first and the transparent window last.


  • Robert G Lewis

    So any alternatives
  • Jayakumar A

    No. You've got two distinct windows here. One for the form, another for the control. You can't draw on both.


  • Drawing on[/underneath!] Controls