Click here to Skip to main content
16,018,949 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
How to do drag drop from one windows form to another windows form ?


What I have tried:

I have tried to used the example like here
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.dodragdrop(v=vs.110).aspx

but what I want is the data is drag from another window form to another window form.
Posted
Updated 20-Jun-16 0:06am
Comments
Maciej Los 20-Jun-16 5:07am    
A source window and destination window may not be the same window. Is there any issue?
Member 12154788 20-Jun-16 5:09am    
You means ?

1 solution

It depends what you are dragging, but...
It's a two stage process: you need to enable drop in the destination form (this uses files)
1) Set the AllowDrop property of your form to True
2) Create a handler for both the DragEnter and DragDrop events of your form.
3) In the DragEnter handler, add the following line of code:
e.Effect = DragDropEffects.Move;

4) In the DragDrop handler, add the following:
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
if (files != null)
    {
    foreach (string file in files)
        {
        Console.WriteLine(file); // Or whatever you need to do...
        }
    }

In your source form, it's a little more complex, as you need to use a control that supports dragging, such as the ListView.
1) Handle the controls ItemDrag event. In this case, a ListView:
C#
private void myListView_ItemDrag(object sender, ItemDragEventArgs e)
    {
    StringCollection s = new StringCollection();
    s.Add(@"D:\Test Data\MyPic.jpg");
    DataObject obj = new DataObject();
    obj.SetFileDropList(s);
    myListView.DoDragDrop(obj, DragDropEffects.Copy);
    }

2) That's it!
 
Share this answer
 
Comments
Member 12154788 20-Jun-16 21:46pm    
Can you explain to me about this code
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
if (files != null)
{
foreach (string file in files)
{
Console.WriteLine(file); // Or whatever you need to do...
}
}
OriginalGriff 21-Jun-16 2:25am    
What part of it do you not understand?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900