Clipboard.ContainsImage()是否可靠甚至有用?

时间:2019-03-28 15:34:18

标签: c# .net winforms locking clipboard

Microsoft文档中针对Clipboard.ContainsImage()提供的示例包括以下内容:

System.Drawing.Image returnImage = null;
if (Clipboard.ContainsImage())
{
    returnImage = Clipboard.GetImage();
    ....
}

此方法的表面/名义上的行为是首先检查剪贴板是否包含图像,如果是,则获取该图像以供使用。否则,返回null

但是,在调用ContainsImage()和调用GetImage()之间的另一个应用程序中,是否有可能改变了剪贴板的内容?毕竟可能没有图像数据。

当剪贴板中没有图像时,GetImage() is documented返回null。很好,但是首先调用ContainsImage()的意义是什么,如果在调用GetImage()时仍然必须检查结果呢?

这不仅仅适用于此示例-如果您实际上需要剪贴板内容,则调用ContainsImage() 有什么用?

也许...

  • 与调用GetImage()相比,它的性能更高,因此即使在少数情况下GetImage()会失败,它仍然值得做什么?

  • 正在进行某种魔术锁定,可以自动解决此问题(高度怀疑)?


ContainsImage()可能有用的情况是,您不需要获取剪贴板内容,而只是查看它们是否为图像。

1 个答案:

答案 0 :(得分:1)

想象一下,如果您有一个按钮,并且想要在剪贴板中有图像时就启用它,否则要禁用它。

定期调用ContainsImage()并不会带来很大的开销,因为它是在将“图像”设置为“剪贴板”时仅设置一次的标志。但是每次获取图像本身只是为了确保剪贴板中有图像是昂贵的。

另一个示例:

想象一下您有byte[]可以包含视频,图像或音频。

public enum MediaType
{
    Audio,
    Video,
    Image,
    None
}

class MyData
{
     private byte mydata = null;
     private MediaType type = MediaType.None;
     public void SetData(byte[] data)
     {
          mydata = data;
          if(ImageValidation())  // a method that validates data is a valid image
              type = MediaType.Image;
          else if(VideoValidation())
              type = MediaType.Video;
          else if(AutioValidation())
              type = MediaType.Audio;
          else
              type = MediaType.None;
     }

     //I'm not going to create all get functions but just for one type

     public bool ContainsImage()   //costless
     {
          return type == MediaType.Image;
     }

     public Image GetImage()  //costly if there is an image
     {
          if(type == MediaType.Image)
              using (var ms = new MemoryStream(mydata))
              {
                   return Image.FromStream(ms);    
              }
          else
              return null;
     }
}