mizuneko
3/3/2013 - 2:35 AM

イベントハンドラを yield return

イベントハンドラを yield return

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

class MyForm : Form
{
  static void Main()
  {
    Application.Run( new MyForm() );
  }

  readonly List<Action<Graphics>> _entities = new List<Action<Graphics>>();
  IEnumerator<MouseEventHandler> _handler;

  public MyForm()
  {
    this.Paint += ( sender, e ) =>
    {
      foreach ( var draw in _entities ) draw( e.Graphics );
    };

    this.MouseClick += ( sender, e ) =>
    {
      if ( _handler != null ) {
        _handler.Current( this, e );
        this.MoveNext();
      }
    };

    _handler = this.DrawLines();
    this.MoveNext();
  }

  void MoveNext()
  {
    if ( !_handler.MoveNext() ) {
      _handler.Dispose();
      _handler = null;
    }
  }

  IEnumerator<MouseEventHandler> DrawLines()
  {
    while ( true ) {
      var p1 = new Point();
      var p2 = new Point();
      yield return ( sender, e ) => p1 = e.Location;
      yield return ( sender, e ) => p2 = e.Location;
      _entities.Add( g => g.DrawLine( new Pen( Brushes.Black ), p1, p2 ) );
      this.Invalidate();
    }
  }
}