Skip to content

Instantly share code, notes, and snippets.

@juner
Created March 15, 2018 04:59
Show Gist options
  • Save juner/508fc79a8df4d680572f1f0489a0ae2e to your computer and use it in GitHub Desktop.
Save juner/508fc79a8df4d680572f1f0489a0ae2e to your computer and use it in GitHub Desktop.
WinForms ControlExtensions Parents() AndParents()
using System.Windows.Forms;
using System.Collections.Generic;
namespace System.Windows.Forms.Extensions
{
/// <summary>
/// コントロールの拡張関数クラス
/// </summary>
public static class ControlExtension
{
/// <summary>
/// 自分の親を返す
/// </summary>
/// <param name="self"></param>
/// <returns></returns>
public static IEnumerable<Control> Parents(this Control self)
{
if (self == null)
yield break;
var c = self;
while((c = c.Parent) != null)
{
yield return c;
}
}
/// <summary>
/// 自分を含めた自分の親を返す
/// </summary>
/// <param name="self"></param>
/// <returns></returns>
public static IEnumerable<Control> AndParents(this Control self)
{
if (self == null)
yield break;
var c = self;
do
{
yield return c;
} while ((c = c.Parent) != null);
}
}
}
@juner
Copy link
Author

juner commented Mar 15, 2018

例えば、Form(=this) 上のcontrol の親子関係とか考えずにそのRectangle表現が欲しいならこうする

var rectangle = new Rectangle(control
    .AndParents()
    .TakeWhile(c => c!= this)
    .Select(c => c.Location)
    .Aggregate(new Point(0,0), (p. l) => {
        p.X += l.X;
        p.Y += l.Y;
        return p;
    }, control.Size);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment