Drag And Drop on Windows Form in C#

This post explains how we can directly drag and drop files on Windows Form.In this post i dynamically change the windows form background by using draganddrop event.Let' s create a new C# Windows Form Application and name it as Drag and Drop.

Right Click on the Windows Form and select "Properties".


In the Properties window under behaviour set AllowDrop to True.


Then create a form events for dragenter and DragandDrop the paste the following code.


Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DragAndDrop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }              

        private void Form1_DragDrop_1(object sender, DragEventArgs e)
        {
            try
            {
                string[] sData = (string[])e.Data.GetData(DataFormats.FileDrop, false);
                foreach(string sFileData in sData)
                {
                    this.BackgroundImage = Image.FromFile(sFileData);
                    this.BackgroundImageLayout = ImageLayout.Stretch;
                    //MessageBox.Show(sFileData);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception:" + ex.ToString());
            }
        }

        private void Form1_DragEnter_1(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }
    }
}


Output:



Download Source Code


No comments :

Post a Comment