拖放文件名 Visual (Managed) C++
Drag & Drop Filename Visual (Managed) C++
我有一个 RichTextBox,我希望允许用户将文件从磁盘拖放到其中。文本框中应该出现的只是文件名。此代码当前将 "System.String[]"
添加到文本框而不是文件名。当我按照 this MSDN 的建议将 DataFormats::FileDrop
更改为 DataFormats::Text
时,出现 NULL 取消引用错误。
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);
}
拖动文件总是会产生一个字符串数组。每个数组元素都是被拖动文件之一的路径。您需要编写额外的代码以将 GetData() 的 return 值转换为数组并迭代它,读取每个文件的内容。类似这样:
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));
}
我有一个 RichTextBox,我希望允许用户将文件从磁盘拖放到其中。文本框中应该出现的只是文件名。此代码当前将 "System.String[]"
添加到文本框而不是文件名。当我按照 this MSDN 的建议将 DataFormats::FileDrop
更改为 DataFormats::Text
时,出现 NULL 取消引用错误。
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);
}
拖动文件总是会产生一个字符串数组。每个数组元素都是被拖动文件之一的路径。您需要编写额外的代码以将 GetData() 的 return 值转换为数组并迭代它,读取每个文件的内容。类似这样:
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));
}