view ServerMonitor/Controls/CheckControl.cs @ 7:8486ab7d2357

Add/remove files
author Brad Greco <brad@bgreco.net>
date Fri, 01 Mar 2019 21:39:22 -0500
parents 3142e52cbe69
children 7127d5b5ac75
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ServerMonitorApp
{
    /// <summary>Base class for check controls</summary>
    /// <remarks>This control should never be used directly, but marking it abstract causes problems with the designer.</remarks>
    public partial class CheckControl : UserControl
    {
        public Type CheckType => GetCheckType(GetType());

        public CheckControl()
        {
            InitializeComponent();
        }

        private void CheckControl_Load(object sender, EventArgs e)
        {
            CheckGroupBox.Text = Helpers.GetDisplayName(CheckType);

            IEnumerable<Panel> panels = CheckGroupBox.Controls.OfType<Panel>();
            foreach (Panel panel in panels)
            {
                CheckBox mainCheckBox = panel.Controls.OfType<CheckBox>().OrderBy(c => c.Left).FirstOrDefault();
                if (mainCheckBox != null)
                {
                    mainCheckBox.CheckedChanged += CheckControl_CheckedChanged;
                    DisablePanelByCheckBox(mainCheckBox);
                }
            }
        }

        private void CheckControl_CheckedChanged(object sender, EventArgs e)
        {
            DisablePanelByCheckBox((CheckBox)sender);
        }

        private void DisablePanelByCheckBox(CheckBox checkBox)
        {
            foreach (Control control in checkBox.Parent.Controls)
            {
                if (control != checkBox)
                    control.Enabled = checkBox.Checked;
            }
        }

        public virtual void LoadCheck(Check check) { }

        public virtual void UpdateCheck(Check check) { }

        public static CheckControl Create(Type CheckType)
        {
            Type checkControlType = typeof(CheckControl).Assembly.GetTypes().FirstOrDefault(t => GetCheckType(t) == CheckType);
            return checkControlType == null ? null : (CheckControl)Activator.CreateInstance(checkControlType);
        }

        private static Type GetCheckType(Type type)
        {
            return type.GetAttribute<CheckTypeAttribute>()?.CheckType;
        }
    }
}