Add code, modify readme.md

This commit is contained in:
intrueder 2013-10-24 02:10:41 +03:00
parent 03e6ee1e16
commit 6c310aa320
2 changed files with 83 additions and 0 deletions

74
Draggable.cs Normal file
View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DraggableControls
{
public static class ControlExtension
{
// TKey is control to drag, TValue is a flag used while dragging
private static Dictionary<Control, bool> draggables =
new Dictionary<Control, bool>();
private static System.Drawing.Size mouseOffset;
/// <summary>
/// Enabling/disabling dragging for control
/// </summary>
public static void Draggable(this Control control, bool Enable)
{
if (Enable)
{
// enable drag feature
if (draggables.ContainsKey(control))
{ // return if control is already draggable
return;
}
// 'false' - initial state is 'not dragging'
draggables.Add(control, false);
// assign required event handlersnnn
control.MouseDown += new MouseEventHandler(control_MouseDown);
control.MouseUp += new MouseEventHandler(control_MouseUp);
control.MouseMove += new MouseEventHandler(control_MouseMove);
}
else
{
// disable drag feature
if (!draggables.ContainsKey(control))
{ // return if control is not draggable
return;
}
// remove event handlers
control.MouseDown -= control_MouseDown;
control.MouseUp -= control_MouseUp;
control.MouseMove -= control_MouseMove;
draggables.Remove(control);
}
}
static void control_MouseDown(object sender, MouseEventArgs e)
{
mouseOffset = new System.Drawing.Size(e.Location);
// turning on dragging
draggables[(Control)sender] = true;
}
static void control_MouseUp(object sender, MouseEventArgs e)
{
// turning off dragging
draggables[(Control)sender] = false;
}
static void control_MouseMove(object sender, MouseEventArgs e)
{
// only if dragging is turned on
if (draggables[(Control)sender] == true)
{
// calculations of control's new position
System.Drawing.Point newLocationOffset = e.Location - mouseOffset;
((Control)sender).Left += newLocationOffset.X;
((Control)sender).Top += newLocationOffset.Y;
}
}
}
}

View File

@ -2,3 +2,12 @@ Control.Draggable
=================
Makes any WinForms control draggable
Usage
-----
```csharp
AnyControl.Draggable(true);
```
Read more: [Draggable WinForms Controls](http://www.codeproject.com/Tips/178587/Draggable-WinForms-Controls)