views:

448

answers:

2

Is there any way to change the BackColor of the border of a panel or similar control?

I am trying to "highlight" the user control when I hover the mouse over the user control.

A: 

You can use the MouseEnter / MouseLeave events to do this.

    private void panel1_MouseEnter(object sender, EventArgs e)
    {
        panel1.BackColor = System.Drawing.Color.Red;
    }

    private void panel1_MouseLeave(object sender, EventArgs e)
    {
        panel1.BackColor = System.Drawing.Color.Empty;
    }
Eoin Campbell
not the panel's backcolor. i want to change the backcolor of the BORDER
ooo
You're question states "the backcolor of a panel or similar control". Re-Edit your question with correct information if you want correct answers
Eoin Campbell
sorry about that . . i have removed the down tick
ooo
+1  A: 

Here's a simple class that highlights controls on the form with a border:

    public class Highlighter : Control
    {
        public void SetTarget(Control c)
        {
            Rectangle r = c.Bounds;
            r.Inflate(3, 3);
            Bounds = r;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            e.Graphics.FillRectangle(Brushes.Red, e.ClipRectangle);
        }
    }

Then, in your form, set everything to use it:

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Control c in Controls)
        {
            c.MouseEnter += mouseEnter;
            c.MouseLeave += mouseLeave;
        }
    }

    private void mouseEnter(object sender, EventArgs e)
    {
        _highlighter.SetTarget(sender as Control);
        _highlighter.Visible = true;
    }

    private void mouseLeave(object sender, EventArgs e)
    {
        _highlighter.Visible = false;
    }

Then, in the constructor, just create the highlighter:

    public Form1()
    {
        InitializeComponent();
        _highlighter = new Highlighter();
        Controls.Add(_highlighter);
    }
Steve Dunn