用户将文件拖到我的 winforms 可执行文件上.我是否创建一些事件侦听器?



我正在从以下链接阅读堆栈溢出文章:打开文件关联应用程序,我遇到了另一个问题,即我的 Windows 窗体应用程序打开,但我看不到内容。在我的应用程序中,我该怎么做才能确保它处理从 Windows 资源管理器打开文件?用户会将一个文件拖到我的 winforms exe 上。

在 WinForms 应用中,您需要从Environment.GetCommandLineArgs方法中获取命令行参数。但是,调用此方法与控制台应用程序时有一个重要的区别:数组中的第一个元素包含正在执行的程序的文件名。如果文件名不可用,则第一个元素等于 String..::。空。其余元素包含在命令行上输入的任何其他标记。我找到了这段代码来存储参数,但我不知道在我的应用程序中实际实现什么事件。在 MSDN 线程上找到以下内容。

[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
string filePath = args[1]; //First arg is the running process
if (File.Exists(filePath))
{
string name = Path.GetFileNameWithoutExtension(filePath);
File.Copy(filePath, name + ".dat");
//todo - delete input
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

用户会将一个文件拖到我的 winforms exe 上。

您需要在目标控件中执行拖放操作。假设它是Form1.

首先,启用AllowDrop属性:

Form1.AllowDrop = true;

处理DragEnter事件以验证操作:

private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var file = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
if (File.Exists(file))
{
e.Effect = DragDropEffects.Move;
return;
}
//If you need to allow certain type of files:
//if (Path.GetExtension(file).Equals(".srcExt", StringComparison.OrdinalIgnoreCase))
//{
//    e.Effect = DragDropEffects.Move;
//    return;
//}
}
e.Effect = DragDropEffects.None;
}

然后,处理DragDrop事件:

private void Form1_DragDrop(object sender, DragEventArgs e)
{
if (e.Effect == DragDropEffects.Move)
{
//according to your snippet:
var srcFile = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
//Another check is good, just in case:
if (File.Exists(srcFile))
{
var destDir = @"The destination Directory";
var destFile = string.Concat(
Path.Combine(
destDir,
Path.GetFileNameWithoutExtension(srcFile)
),
".dat"
);
File.Move(srcFile, destFile);
}
}
}

至于Main部分,我相信@Jimi在他的评论中已经完美地涵盖了这一点,所以让我们从他那里窃取一些来完成这篇文章:

[STAThread]
static void Main(string[] args)
{
if(args.Length > 0 && File.Exists(args[0]))
{
var srcFile = args[0];
var destDir = @"The destination Directory";
var destFile = string.Concat(
Path.Combine(
destDir,
Path.GetFileNameWithoutExtension(srcFile)
),
".dat"
);
File.Move(srcFile, destFile);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());            
}

祝你好运。

最新更新