Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a border to a custom control in the design view?

Transparent images are pure evil in Windows Forms, that why I've created a custom control class to handle them. The designer doesn't show my control when it's empty. I would like to add a subtle border, but only in the design view (and when no border is added by the user). How would I do this?

My class is:

class TransparentImage : Control
{
    public Image Image { get; set; }

    protected Graphics graphics;

    public string FilePath { get; set; }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        // Don't paint background
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // Update the private member so we can use it in the OnDraw method
        this.graphics = e.Graphics;

        // Set the best settings possible (quality-wise)
        this.graphics.TextRenderingHint =
            System.Drawing.Text.TextRenderingHint.AntiAlias;
        this.graphics.InterpolationMode =
            System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        this.graphics.PixelOffsetMode =
            System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        this.graphics.SmoothingMode =
            System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        if (Image != null)
        {
            // Sets the images' sizes and positions
            var width = Image.Size.Width;
            var height = Image.Size.Height;
            var size = new Rectangle(0, 0, width, height);

            // Draws the two images
            this.graphics.DrawImage(Image, size);
        }
    }
}
like image 586
Bert Bakker Avatar asked Jan 03 '16 19:01

Bert Bakker


1 Answers

Check if (this.DesignMode) in your OnPaint and call DrawRectangle.

You may want to use a new Pen(SystemColors.ActiveBorder) { DashStyle = DashStyle.Dot }

like image 117
SLaks Avatar answered Sep 28 '22 08:09

SLaks