Search code examples
c#user-interfacedrag-and-drop

Drag and drop - user interface query


c# winforms -I am trying to improve my app by having some drag drop functionality. - This is all working fine - but i would like to show a "Box" with text such as "Drop Here" when the form is dragged over as a target for the drop. i can get the picture box to display in that manner when drag enters the form, however the picture box will not accept the drop.

The drop data will either be a file or a web address - again i can manage the identification of that, the only thing i need to do is to get the picture box to accept the drop, and that does not appear to be possible

Thanks


Solution

  • A simple example, place a Label on top of a TextBox. Set visibility of the Label to false.

    • In DragEnter event of the TextBox, set the label Visible to true
    • In DragLeave event of the TextBox, set the label Visible to false
    • In DragDrop event of the TextBox, set the label Visible to false

    Here the TextBox name is FolderTextBox and our label is ShowHelpLabel.

    private void FolderTextBox_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            e.Effect = DragDropEffects.Copy;
            ShowHelpLabel.Visible = true;
        }
    }
    
    private void FolderTextBox_DragLeave(object sender, EventArgs e)
    {
        ShowHelpLabel.Visible = false;
    }
    
    private void FolderTextBox_DragDrop(object sender, DragEventArgs e)
    {
        var droppedData = (string[])e.Data.GetData(DataFormats.FileDrop);
    
        if (!Directory.Exists(droppedData[0])) return;
        ShowHelpLabel.Visible = false;
        FolderTextBox.Text = droppedData[0];
    }
    

    Full source for above which is a simple utility.

    enter image description here