Visual Basic 或 C# 拖放图像源 url

Visual Basic or C# drag and drop image source url

我想创建和编译一个小程序,允许某人 运行 从浏览器拖放图像。然后,我希望该程序选择该图像的来源 URL 并将其粘贴到文本框表单中。我需要这样做,因为稍后我会让程序使用 API 单击按钮将上述 URL 图像上传到 Imgur,但现在我正在寻找一种方法使用拖放对我有利。我也不知道使用 VB.net 或 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;
            }
        }
    }
}

question you linked 中的解决方案似乎只适用于 某些 浏览器。在 GetData 中使用 "FileContents" 对我来说在 Chrome 中不起作用,但适用于 Firefox。 DataFormats.Dib 将允许您直接使用位图,但不幸的是 Chrome 似乎也不支持这一点。

指定 DataFormats.Text 似乎是一个可靠的跨浏览器解决方案,因为它 returns 图像的 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;
// ...