Goodies
Goodies

Reputation: 4681

Drag & Drop Filename Visual (Managed) C++

I have a RichTextBox that I would like to allow a user to drag and drop a file from disk into. All that should appear in the textbox is the filename(s). This code currently adds "System.String[]" to the textbox instead of the filename. When I change the DataFormats::FileDrop to DataFormats::Text as this MSDN would seem to suggest, I get a NULL dereference error.

The RichTextBox name is rtbFile. In my constructor, I have:

this->rtbFile->AllowDrop = true;

I set up the events like this (within InitializeComponents):

this->rtbFile->DragEnter += gcnew System::Windows::Forms::DragEventHandler(this, &VanicheMain::rtbFile_DragEnter);
this->rtbFile->DragDrop += gcnew System::Windows::Forms::DragEventHandler(this, &VanicheMain::rtbFile_DragDrop);

The functions are defined as follows:

void rtbFile_DragEnter(System::Object ^sender, System::Windows::Forms::DragEventArgs ^ e) {
    if (e->Data->GetDataPresent(DataFormats::FileDrop))
        e->Effect = DragDropEffects::Copy;
    else
        e->Effect = DragDropEffects::None;
}

System::Void rtbFile_DragDrop(System::Object ^sender, System::Windows::Forms::DragEventArgs ^e){
    int i = rtbFile->SelectionStart;;
    String ^s = rtbFile->Text->Substring(i);
    rtbFile->Text = rtbFile->Text->Substring(0, i);
    String ^str = String::Concat(rtbFile->Text, e->Data->GetData(DataFormats::FileDrop)->ToString());
    rtbFile->Text = String::Concat(str, s);
}

Upvotes: 3

Views: 1252

Answers (1)

Hans Passant
Hans Passant

Reputation: 941208

Dragging files always produces an array of strings. Each array element is the path to one of the files that are dragged. You'll need to write the extra code to cast the return value of GetData() to an array and iterate it, reading the content of each file. Similar to this:

array<String^>^ paths = safe_cast<array<String^>^>(e->Data->GetData(DataFormats::FileDrop));
for each (String^ path in paths) {
    String^ ext = System::IO::Path::GetExtension(path)->ToLower();
    if (ext == ".txt") rtbFile->AppendText(System::IO::File::ReadAllText(path));
}

Upvotes: 5

Related Questions