Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# - Determine if file copied into clipboard is an image

The user right clicks on a file(say on the desktop) and clicks 'copy' . Now how do I determine in C# if the file copied to the clipboard is an image type ?

Clipboard.ContainsImage() doesn't work in this case

The following determines if an image is directly copied to the clipboard, not if a file is copied to the clipboard

   IDataObject d = Clipboard.GetDataObject();

   if(d.GetDataPresent(DataFormats.Bitmap))
   {
       MessageBox.Show("image file found");
   }

To be clear I want to determine if the 'file' copied to the clipboard is an image.

Edit: the answers are great, but how do I get the filename of a file copied to the clipboard ? Clipboard.getText() doesn't seem to work.. Edit2: Clipboard.GetFileDropList() works

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can check it like this (There is no built in way of doing this) Read the file and use it in a Graphics Image Object if it will be image it will work fine else it will Raise an OutOfMemoryException.

here is a sample code:

 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;
  }

It will work for BMP, GIF, JPEG, PNG, TIFF file formats


Update

Here is the code to get the FileName:

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...