Sina Iravanian

I blog about software development

Drawing a RedBorder Around Controls in Windows Forms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
private Form _parentForm;

private ToolTip _errorToolTip;
private ToolTip ErrorToolTip
{
    get { return _errorToolTip ?? (_errorToolTip = new ToolTip()); }
}

private void SetError(Control control, string value)
{
    // ....

    if (_parentForm == null)
    {
        _parentForm = control.FindForm();
        if (_parentForm != null)
            _parentForm.Paint += BorderPaintEventHandler;

    }
    ErrorToolTip.SetToolTip(control, String.IsNullOrWhiteSpace(value) ? null : value);
    if (_parentForm != null)
        _parentForm.Refresh();
    break;

    // ....
}

private void BorderPaintEventHandler(object sender, PaintEventArgs args)
{
    if (_parentForm == null || _controls.Count == 0)
        return;

    foreach (var ctrl in _controls)
    {
        var bounds = ctrl.Bounds;
        var activeCountrolBounds = new Rectangle(bounds.Left - 1, bounds.Top - 1, bounds.Width + 1, bounds.Height + 1);
        ctrl.Parent.CreateGraphics().DrawRectangle(Pens.Red, activeCountrolBounds);
    }
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        if (_errorToolTip != null)
            _errorToolTip.Dispose();

        if (_parentForm != null)
            _parentForm.Paint -= BorderPaintEventHandler;

        _controls.Clear();
    }

    base.Dispose(disposing);
}

Comments