用户右键单击文件(例如在桌面上)并单击“复制”。现在如何在 C# 中确定复制到剪贴板的文件是否是图像类型?
Clipboard.ContainsImage() 在这种情况下不起作用
下面判断是否将图像直接复制到剪贴板,而不是文件是否复制到剪贴板
IDataObject d = Clipboard.GetDataObject();
if(d.GetDataPresent(DataFormats.Bitmap))
{
MessageBox.Show("image file found");
}
为了清楚起见,我想确定复制到剪贴板的“文件”是否是图像。
编辑:答案很好,但是如何获取复制到剪贴板的文件的文件名? Clipboard.getText() 似乎不起作用.. Edit2: Clipboard.GetFileDropList() 有效
你可以这样检查(没有内置的方法可以做到这一点)
读取文件并在图形图像对象中使用它,如果它是图像,它将正常工作,否则它将引发OutOfMemoryException
.
这是示例代码:
bool IsAnImage(string filename)
{
try
{
Image newImage = Image.FromFile(filename);
}
catch (OutOfMemoryException ex)
{
// Image.FromFile will throw this if file is invalid.
return false;
}
return true;
}
它适用于 BMP、GIF、JPEG、PNG、TIFF 文件格式
Update
这是获取文件名的代码:
IDataObject d = Clipboard.GetDataObject();
if(d.GetDataPresent(DataFormats.FileDrop))
{
//This line gets all the file paths that were selected in explorer
string[] files = d.GetData(DataFormats.FileDrop);
//Get the name of the file. This line only gets the first file name if many file were selected in explorer
string TheImageFile = files[0];
//Use above method to check if file is Image file
if(IsAnImage(TheImageFile))
{
//Process file if is an image
}
{
//Process file if not an image
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)