如何将选中的文本从firefox拖放到我的winform应用程序?

时间:2012-11-30 00:41:41

标签: c# winforms

我正在尝试将一些随机选择的文本从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);
    }

4 个答案:

答案 0 :(得分:0)

这应该让你入门

    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);
    }

答案 1 :(得分:0)

对于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);
    }

}

答案 2 :(得分:0)

在Windows 7上,当Firefox以较低权限运行时,以管理员身份运行Visual Studio时,它可能无法运行。请参阅此答案:C# Drag drop does not work on windows 7

在Visual Studio外部运行程序就可以了。

答案 3 :(得分:0)

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