Skip to content

Instantly share code, notes, and snippets.

@tfwio
Last active September 20, 2015 14:49
Show Gist options
  • Save tfwio/2c5b032fcec0b5387ca4 to your computer and use it in GitHub Desktop.
Save tfwio/2c5b032fcec0b5387ca4 to your computer and use it in GitHub Desktop.
Quick 'DropIn' to apply DragDrop operations to a WinForms with particular attention to dragging a file into TextBox. [tags=csharp,dragdrop,csharp-extension]
// tfwio ;)
using System;
namespace System.Windows.Forms
{
/// <summary>
/// Apply DragDrop actions indirectly using delegtes or EventHandlers,
/// or directly with Action definitions (see Example).
/// </summary>
/// <seealso cref="ApplyDefaultDragDrop(TextBox)"/>
/// <example>
/// <code><pre>
/// this.ApplyDragDropMethod(
/// (sender,e)=>{
/// if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
/// },
/// (sender,e)=>{
/// if (e.Data.GetDataPresent(DataFormats.FileDrop))
/// {
/// var strFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
/// var file = new FileInfo(strFiles[0]);
/// strFiles = null;
/// Gogo(file);
/// }
/// });</pre></code>
/// </example>
static class DragDropFormsExtension
{
/// <seealso cref="ApplyDefaultDragDrop(TextBox)"/>
/// <example>
/// <code><pre>
/// this.ApplyDragDropMethod(
/// (sender,e)=>{
/// if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
/// },
/// (sender,e)=>{
/// if (e.Data.GetDataPresent(DataFormats.FileDrop))
/// {
/// var strFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
/// var file = new FileInfo(strFiles[0]);
/// strFiles = null;
/// Gogo(file);
/// }
/// });</pre></code>
/// </example>
static public void ApplyDragDropMethod(this Control tInput, DragEventHandler TInputDragEnter, DragEventHandler TInputDragDrop)
{
// dragdrop
tInput.AllowDrop = true;
tInput.DragEnter += TInputDragEnter;
tInput.DragDrop += TInputDragDrop;
}
/// <seealso cref="ApplyDragDropMethod(Control,DragEventHandler,DragEventHandler)"/>
static public void ApplyDefaultDragDrop(this TextBox tInput)
{
tInput.ApplyDragDropMethod(Event_TInputDragEnter, Event_TInputDragDrop);
}
internal static void Event_TInputDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
internal static void Event_TInputDragDrop(object sender, DragEventArgs e)
{
TextBox tInput = sender as TextBox;
if (tInput == null)
throw new Exception("Something went very wrong!");
if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
string[] strFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
tInput.Text = strFiles[0];
strFiles = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment