[英]Drag and drop from windows explorer to custom C# app that actually works with Windows 7
我尝试(使用几十个例子)创建一个简单的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中运行吗?
我已经尝试了你的样品,它工作正常。 检查是否已将Load事件挂钩到Form1_Load处理程序的表单对象,并且您的命名空间是相同的。
this.Load += new System.EventHandler(this.Form1_Load);
或通过属性编辑器:
好吧,我发现在管理员下运行VS(我必须为另一个项目做)是罪魁祸首。 在正常用户模式下加载VS,它可以在UAC上正常工作。 谢谢大家的投入!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.