0

我尝试(使用几十个示例)创建一个简单的 WinForms 应用程序,该应用程序允许我将一个简单的文本文件拖放到自定义 DotNet 程序的输入框中。不幸的是,似乎没有在 Windows 7 中实际运行的示例。

这是一个简单的例子(来自另一篇被到处引用的帖子),但它根本不起作用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace DragAndDropTestCSharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.AllowDrop = true;
        this.DragEnter += Form1_DragEnter;
        this.DragDrop += Form1_DragDrop;
    }
    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            e.Effect = DragDropEffects.Copy;
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
            foreach (string fileLoc in filePaths)
            {
                // Code to read the contents of the text file
                if (File.Exists(fileLoc))
                {
                    using (TextReader tr = new StreamReader(fileLoc))
                    {
                        MessageBox.Show(tr.ReadToEnd());
                    }
                }

            }
        }
    }
}
}

这可能是UAC问题吗?如果是这样,为什么世界上所有其他应用程序似乎都在使用 UAC 进行这种简单但难以捉摸的拖放壮举?

有人有一个真实可行的例子来让它在 Windows 7 中工作吗?

4

2 回答 2

1

我试过你的样品,效果很好。检查您是否已将表单对象的 Load 事件挂钩到 Form1_Load 处理程序,并且您的命名空间是否相同。

this.Load += new System.EventHandler(this.Form1_Load);

或通过属性编辑器:

属性加载处理程序

于 2013-04-12T16:57:27.980 回答
1

好的,我发现在管理员下运行 VS(我必须为另一个项目做)是罪魁祸首。在普通用户模式下加载 VS,它可以在 UAC 上正常工作。感谢大家的意见!

于 2013-04-14T22:08:26.930 回答