2016-02-01 36 views
1

我有一個RichTextBox,我想允許用戶將文件從磁盤拖放到。所有應該出現在文本框中的是文件名。此代碼當前將"System.String[]"添加到文本框而不是文件名。當我將DataFormats::FileDrop更改爲DataFormats::Text,因爲this MSDN似乎暗示,我得到一個NULL解引用錯誤。拖放文件名Visual(託管)C++

RichTextBox名稱是rtbFile。在我的構造函數中,我有:

this->rtbFile->AllowDrop = true; 

我設置這樣的事件(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); 

的功能定義如下:

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); 
} 
+0

對,我正在使用FileDrop。問題是它打印出「System.String []」而不是文件名。我真的很想獲得文件名。 – Goodies

+0

你能舉個例子嗎? – Goodies

+0

LoadFile函數將文件路徑作爲參數。另外,^ str變量顯然不是一個數組。 – Goodies

回答

2

文件拖動總是產生一個字符串數組。每個數組元素是被拖動的其中一個文件的路徑。您需要編寫額外的代碼來將GetData()的返回值轉換爲數組並對其進行迭代,從而讀取每個文件的內容。類似於:

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)); 
} 
+0

我寫了幾乎完全相同的東西,正在根據您的意見回答我自己的問題。我得到了它的工作。謝謝。 – Goodies