Determine if the file is copied to the clipboard.

The user right-clicks on the file (say, on the desktop) and clicks “copy”. Now, how to determine in C # if the file copied to the clipboard is an image type?

Clipboard.ContainsImage () in this case does not work

Next, it is determined whether the image will be copied directly to the clipboard, and not if the 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 name of the file copied to the clipboard? Clipboard.getText () doesn't seem to work .. Edit2: Clipboard.GetFileDropList () works

+6
c #
source share
3 answers

You can check it like this (there is no built-in way to do this) Read the file and use it in the graphic image object, if it is displayed, it will work fine, otherwise 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 in the formats BMP, GIF, JPEG, PNG, TIFF


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 } } 
+6
source share

Get the file name from the clipboard (copying the file to the clip code simply copies its name). Then check if the files are images.

There are two ways to do this:

  • By file extension
  • Open the file and check the magic flags indicating common image formats.

I prefer the second because it works even if the file has the wrong extension. On slow media, this can be slower, although you need to access the file, and not just work with the file name that you received from the clipboard.

+3
source share

You can easily check the clipboard if it contains an image or not:

 if (Clipboard.ContainsImage()) { MessageBox.Show("Yes this is an image."); } else { MessageBox.Show("No this is not an image!"); } 
0
source share

All Articles