簡體   English   中英

將圖像從瀏覽器拖放到WPF應用程序

[英]Drag and Drop image from browser to WPF Application

我正在嘗試在WPF應用程序中實現功能,以將圖像從瀏覽器拖到WPF應用程序的窗口中。

該代碼在Firefox和Windows資源管理器中可以正常運行,但是在Chrome和IE中會出現問題(尚未嘗試使用任何其他瀏覽器)。

這是一個代碼片段:

private void Drag_Enter(object sender, DragEventArgs e)
{
    foreach (string format in e.Data.GetFormats())
        Console.WriteLine(format);
    Console.WriteLine("Effects:" + e.AllowedEffects);
}

private void Drag_Drop(object sender, DragEventArgs e)
{
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    ImageSourceConverter converter = new ImageSourceConverter();
    foreach (string file in files)
    {
        if (converter.IsValid(file))
        {
            // Do something with the image
        }
    }
 }

查看輸出,看來Firefox實際上是將圖像保存到剪貼板中,而Chrome只是在抓取圖像的html,而IE對此不做任何事情。

任何人都對我如何獲得跨瀏覽器功能有一些見識?


更新 :我發現了幾種解決方法,分別是解析圖像源的html(Chrome / Firefox),然后使用WebClient對象之類的源從源中下載。 不過,我們更願意使用一種更能檢查文件類型的方法。

IE9和Firefox都具有DeviceIndependentBitmap文件格式,該格式在拖動非超鏈接圖像時可用。 盡管Chrome似乎不支持它,但這似乎是一種更安全的選擇。 對於超鏈接圖像也不是那么有用。


使用Firefox,輸出為(由於某種原因,Drag_Enter被觸發兩次):

text/x-moz-url
FileGroupDescriptor
FileGroupDescriptorW
FileContents
UniformResourceLocator
UniformResourceLocatorW
text/x-moz-url-data
text/x-moz-url-desc
text/uri-list
text/_moz_htmlcontext
text/_moz_htmlinfo
text/html
HTML Format
Text
UnicodeText
System.String
application/x-moz-nativeimage
DeviceIndependentBitmap
FileDrop
FileNameW
FileName
Preferred DropEffect
application/x-moz-file-promise-url
application/x-moz-file-promise-dest-filename
DragImageBits
DragContext
Effects: Link, All

Chrome(drag_enter也被觸發兩次):

DragContext
DragImageBits
FileGroupDescriptorW
FileContents
HTML Format
text/html
text/x-moz-url
UniformResourceLocatorW
UniformResourceLocator
Text
UnicodeText
System.String
Effects: Copy, Move, Link

Internet Explorer(再次,drag_enter被觸發兩次):

UntrustedDragDrop
msSourceUrl
FileGroupDescriptor
FileGroupDescriptorW
FileContents
UniformResourceLocator
Effects: Link

您可以使用FileGroupDescriptorW和FileContent格式來獲取數據。

  • FileGroupDescriptorW是描述您數據的FileDescriptors數組(例如:名稱,大小,修改時間,...)
  • FileContent包含您的文件內容。

如果您不關心文件名而只需要二進制內容,則可以使用

var filestream = (MemoryStream[])dataObject.GetData("FileContents");

如果您想獲得有關如何使用FileGroupDescriptor(W)的更深入的指導,我可以在codeproject.com上推薦本教程 它討論了從MS Outlook中進行拖放的問題,但是它使用相同的IDataObject格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM