【问题标题】:How can I drag and drop selected text from firefox to my winform app?如何将选定的文本从 firefox 拖放到我的 winform 应用程序?
【发布时间】:2012-11-30 00:41:41
【问题描述】:

我正在尝试将一些随机选择的文本从 Firefox 中的随机网页拖放到我的 Winform 应用程序的文本框中,但由于某种原因,我无法让它工作。我在控件(文本框)上将 AllowDrop 设置为 true,并且我正在处理 DragEnter 和 DragDrop 事件,所以这不是问题。任何人都知道问题可能是什么?

我的代码如下所示:

    public Form1()
    {
        InitializeComponent();

        tbISBN.DragDrop += new DragEventHandler(tbISBN_DragDrop);
        tbISBN.DragEnter += new DragEventHandler(tbISBN_DragEnter);
        tbISBN.AllowDrop = true;           
    }

    void tbISBN_DragEnter(object sender, DragEventArgs e)
    {
        foreach (var param in e.Data.GetFormats())
            Console.WriteLine(param);

        if ((e.AllowedEffect & DragDropEffects.All) != 0 && e.Data.GetDataPresent(typeof(string)))
        {
            e.Effect = DragDropEffects.All;
        }
    }

    void tbISBN_DragDrop(object sender, DragEventArgs e)
    {
        string stringData = e.Data.GetData(typeof(string)) as string;
        MessageBox.Show(stringData);
    }

【问题讨论】:

  • 如果它不起作用,你怎么知道你正在正确处理事件?

标签: c# winforms


【解决方案1】:

这应该让你开始

    public Form1()
    {
        InitializeComponent();
        AllowDrop = true;
        DragEnter += new DragEventHandler(Form1_DragEnter);
        DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e)
    {
        if ((e.AllowedEffect & DragDropEffects.All) != 0 && e.Data.GetDataPresent(typeof(string)))
        {
            e.Effect = DragDropEffects.All;
        }
    }

    void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string stringData = e.Data.GetData(typeof(string)) as string;
        MessageBox.Show(stringData);
    }

【讨论】:

  • 我试过你的例子,但仍然没有运气!如果我从 Visual Studios 控制台/输出窗口中选择一些文本,那么我可以将其拖放到文本框中,但我仍然无法从 Firefox 拖放文本!
【解决方案2】:

对于 DragEnter 和 DragDrop,您应该说明要处理的数据类型。 对于来自 Firefox 的文本,如果您想要文本字符串本身,则应使用 StringFormatText 也可以,但不是那么灵活。

这适用于 Firefox 中的所有纯文本。当您复制属于链接的文本时,您将收到超链接目标。

void MainFormDragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.StringFormat)) 
        e.Effect = DragDropEffects.Copy;
}

void MainFormDragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.StringFormat)) {
        string dropText = (string)e.Data.GetData(DataFormats.StringFormat);
        Debug.WriteLine(dropText);
    }

}

【讨论】:

    【解决方案3】:

    在 Windows 7 上,当您以管理员身份运行 Visual Studio 而 Firefox 以较低权限运行时,它可能无法正常工作。看到这个答案:C# Drag drop does not work on windows 7

    在 Visual Studio 之外运行程序就可以解决问题。

    【讨论】:

      【解决方案4】:

      使用e.Data.GetData(DataFormats.Html) 检索文本和源 URL,或使用e.Data.GetData(DataFormats.Text 仅检索文本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        相关资源
        最近更新 更多