2016-02-14 21 views
1

我想創建並編譯一個小程序,允許某人從瀏覽器中運行,拖放圖像。然後我想讓這個程序挑出這個圖像的源URL並將其粘貼到文本框中。我需要這樣做,因爲我稍後將使程序通過使用API​​單擊按鈕將上述URL圖像上傳到Imgur,但現在我正在尋找一種方法來使用拖放功能我的優勢。我也不知道是否會更容易使用VB.net或C#。Visual Basic或C#拖放圖像源地址

有人可以給我任何線索,我可以做到這一點嗎?

這裏是我迄今爲止..

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Imgur_Album_Upload 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      WireDragDrop(this.Controls); 
     } 
     private void WireDragDrop(Control.ControlCollection ctls) 
     { 
      foreach (Control ctl in ctls) 
      { 
       ctl.AllowDrop = true; 
       ctl.DragEnter += ctl_DragEnter; 
       ctl.DragDrop += ctl_DragDrop; 
       WireDragDrop(ctl.Controls); 

      } 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void ctl_DragDrop(object sender, DragEventArgs e) 
     { 
      var textData = e.Data.GetData(DataFormats.Text) as string; 

      if (textData == null) 
       return; 

      messagebox.Text = textData; 
      // Validate the URL in textData here 
     } 
     private void ctl_DragEnter(object sender, DragEventArgs e) 
     { 
      if (e.Data.GetDataPresent(DataFormats.Text)) 
      { 
       e.Effect = DragDropEffects.Move; 
      } 
      else 
      { 
       e.Effect = DragDropEffects.None; 
      } 
     } 
    } 
} 
+0

在這種情況下,您需要瀏覽器本身的幫助。 –

+0

我已經做了很多研究,沒有什麼比較有效的,只是想知道是否有人有任何想法,因爲我運氣不佳 – user4191887

+0

我認爲它會像剪貼板抓取一樣工作很多,但這次是一個拖-drop – user4191887

回答

1

question you linked的解決方案似乎只與一些瀏覽器工作。使用GetData中的「FileContents」在Chrome中無法使用,但適用於Firefox。 DataFormats.Dib將允許您直接使用位圖,但不幸的是,Chrome似乎也不支持這一點。

指定DataFormats.Text似乎是一個可靠的跨瀏覽器解決方案,因爲它會返回圖像的URL與我測試過的所有瀏覽器。 DataFormats.UnicodeText可能會更好,但我沒有測試它。

首先,AllowDrop屬性設置爲true在哪個控制要應對拖動和下降。然後,添加這些事件處理程序的DragEnterDragDrop事件:

private void DragEnterHandler(object sender, DragEventArgs e) 
{ 
    if (e.Data.GetDataPresent(DataFormats.Text)) 
    { 
     e.Effect = DragDropEffects.Move; 
    } 
    else 
    { 
     e.Effect = DragDropEffects.None; 
    } 
} 

private void DragDropHandler(object sender, DragEventArgs e) 
{ 
    var textData = e.Data.GetData(DataFormats.Text) as string; 

    if (textData == null) 
     return; 

    MessageBox.Show(textData); 
    // Validate the URL in textData here 
} 

Visual Studio的設計師可以爲你做到這一點。或者,您可以自己添加處理程序,例如在窗體的構造函數中:

this.DragEnter += DragEnterHandler; 
this.DragDrop += DragDropHandler; 
// someControl.DragEnter += DragEnterHandler; 
// ... 
+0

你將如何做到這一點,所以你可以拖動圖像上的任何地方的圖像,它會進入它進入消息框?我認爲這不足以要求您將其拖到消息框中。 – user4191887

+0

@ user4191887我希望[this](http://stackoverflow.com/a/17014821/996081)回答有幫助。 – cubrr

+0

我試過了,它仍然不起作用,當我將它拖到文本框中時,它只是打開一個對話框,其中包含圖像url – user4191887