获取从资源管理器拖放数据到 Windows 表单的文件名
Get the filename of drag&drop data from explorer to Windows Forms
我正在努力完成我认为会很简单的任务。
我有一个用 C++/CLI 编写的 Windows Forms 应用程序。我希望用户能够将文件拖放到表单中以进行某种处理。
我已将表单行为设置为 AllowDrop 并引发 DragEnter 事件。
如何检索文件名?我看到 this example in C# 但没有成功移植到 C++/CLI
这是我试过的:
private: System::Void tabSingle_DragEnter(System::Object^ sender,
System::Windows::Forms::DragEventArgs^ e)
{
if ( e->Effect == DragDropEffects::Link)
{
// This is true
}
try
{
String^ filename = (String^) e->Data->GetData("FileName");
}
catch(...)
{
// System.InvalidCastException: Impossible to convert an object of type 'System.String[]' in to'System.String'
}
}
提前致谢!
编辑: 我用收到的异常描述更新了答案。看起来预期的对象是 System.String[]。我应该如何修改该行以使其具有与 C# 上的这一行相同的行为(来自 here)
Array data=((IDataObject)e.Data).GetData("FileName") as Array;
C++/CLI 中的数组语法是array<String^>^ filenames = ...
。
因为异常告诉您您有一个字符串数组,所以直接转换为该类型,而不是通用类型 Array
,就像他们在 C# 示例中所做的那样。 (自然是在使用之前先检查一下是不是字符串数组等等)
我正在努力完成我认为会很简单的任务。
我有一个用 C++/CLI 编写的 Windows Forms 应用程序。我希望用户能够将文件拖放到表单中以进行某种处理。
我已将表单行为设置为 AllowDrop 并引发 DragEnter 事件。
如何检索文件名?我看到 this example in C# 但没有成功移植到 C++/CLI
这是我试过的:
private: System::Void tabSingle_DragEnter(System::Object^ sender,
System::Windows::Forms::DragEventArgs^ e)
{
if ( e->Effect == DragDropEffects::Link)
{
// This is true
}
try
{
String^ filename = (String^) e->Data->GetData("FileName");
}
catch(...)
{
// System.InvalidCastException: Impossible to convert an object of type 'System.String[]' in to'System.String'
}
}
提前致谢!
编辑: 我用收到的异常描述更新了答案。看起来预期的对象是 System.String[]。我应该如何修改该行以使其具有与 C# 上的这一行相同的行为(来自 here)
Array data=((IDataObject)e.Data).GetData("FileName") as Array;
C++/CLI 中的数组语法是array<String^>^ filenames = ...
。
因为异常告诉您您有一个字符串数组,所以直接转换为该类型,而不是通用类型 Array
,就像他们在 C# 示例中所做的那样。 (自然是在使用之前先检查一下是不是字符串数组等等)