Skip to content

Instantly share code, notes, and snippets.

@WildGenie
Created January 3, 2017 01:40
Show Gist options
  • Save WildGenie/9a688ed6e42e4f59407e88a392efd5c8 to your computer and use it in GitHub Desktop.
Save WildGenie/9a688ed6e42e4f59407e88a392efd5c8 to your computer and use it in GitHub Desktop.
public static class FormExtensions
{
public static void EnableDragging(this Control c)
{
// Long way, but strongly typed.
var downs =
from down in Observable.FromEvent<MouseEventHandler, MouseEventArgs>(
eh => new MouseEventHandler(eh),
eh => c.MouseDown += eh,
eh => c.MouseDown -= eh)
select new { down.EventArgs.X, down.EventArgs.Y };
// Short way.
var moves = from move in Observable.FromEvent<MouseEventArgs>(c, "MouseMove")
select new { move.EventArgs.X, move.EventArgs.Y };
var ups = Observable.FromEvent<MouseEventArgs>(c, "MouseUp");
var drags = from down in downs
from move in moves.TakeUntil(ups)
select new Point { X = move.X - down.X, Y = move.Y - down.Y };
drags.Subscribe(drag => c.SetBounds(c.Location.X + drag.X, c.Location.Y + drag.Y, 0, 0, BoundsSpecified.Location));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment