How can we take advantage of WindowsFroms composite pattern

We can extend all of our controls by this code:

public static class WinFormsExtension
    {
        public static T GetControl<T>(this Control parent) where T : Control
        {
            if (parent != null)
            {
                foreach (Control control in parent.Controls)
                {
                    if (!(control is T))
                    {
                        continue;
                    }

                    return (T)control;
                }
            }

            return null;
        }

        public static T GetControl<T>(this Control parent, string name) where T : Control
        {
            if (parent != null)
            {
                foreach (Control control in parent.Controls)
                {
                    if (!(control is T))
                    {
                        continue;
                    }

                    if (!String.Equals(control.Name, name))
                    {
                        continue;
                    }

                    return (T)control;
                }
            }

            return null;
        }
    }

Advantages:

  • Simple looking for control -> first control of T type or control of T type with Name equal to name is returned by control.GetControl() or control.GetControl(“simpleName”)
  • If we want to create automation tool executing operations on WinForms (and looking for the controls by the code) this solution will be very helpful
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s