【问题标题】:C#: Drag & Drop File on .exe (icon) and get filepathC#:在 .exe(图标)上拖放文件并获取文件路径
【发布时间】:2015-04-29 06:04:45
【问题描述】:

我是 C# 新手,我无法解决这个问题。这是我想要实现的目标。 每当我将文件拖放到 .exe 文件上(在图标本身上)时,应用程序应该捕获被拖动文件的文件路径。

谢谢。

【问题讨论】:

  • 你试过用谷歌搜索你的问题吗?有没有为自己寻找解决方案的尝试?
  • 您正在开发什么应用程序..更具体。
  • 是的,帕特里克。当我失败时,那是我在这里注册以获得答案的时候。无论如何,我会尝试您提供的链接。谢谢。
  • @约瑟夫。重点是获取放在 exe 图标上的文件的文件路径。稍后将在代码中使用此文件路径来打开该特定文件。简而言之 - 在这个 exe 上拖放文件,文件应该打开。如果您需要更多详细信息,请告诉我。谢谢。

标签: c# drag-and-drop


【解决方案1】:

如果我理解正确,您希望将文件拖放到 exe 的图标上,而不是应用程序本身。如果是这样,则可以使用传递给应用程序的参数轻松实现。如果您在制作控制台应用程序时检查原始样板代码,它具有应用程序入口点:

static void Main(string[] args)

如果您将文件拖放到应用程序的图标上,args[0] 将保存被拖放文件的名称。如果目标是将文件拖放到 EXE 文件中,有很多关于 SO 的教程。

【讨论】:

  • 谢谢安德烈。我刚刚开始学习这项技术。我错过了一个如此愚蠢的人。顺便再次感谢。
【解决方案2】:

如果您编写以下代码,那么当您将文件拖到 exe 图标上时,args[0] 会将其路径作为参数保存: (我添加了 if 语句,如果您在不拖动任何东西的情况下启动程序 它不应该崩溃)

class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.WriteLine(args[0]);
            }
            Console.ReadLine();
        }
    }

【讨论】:

    【解决方案3】:

    通过将默认的string[] args 添加到Main 中的Main 函数,我能够将拖放添加到使用Windows 窗体创建的可执行文件/快捷方式上。然后,将相同的参数添加到Form1 的构造函数中,并传入从Main 收集的相同的args

    Program.cs

    static class Program
    {
        [STAThread]
        //add in the string[] args parameter
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //pass in the args to the form constructor
            Application.Run(new Form1(args));
        }
    }
    

    Form1.cs

    //add in the string[] args parameter to the form constructor
    public Form1(string[] args)
    {
        InitializeComponent();
    
        //if there was a file dropped..
        if (args.Length > 0)
        {
            var file = args[0];
            //do something with the file now...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      相关资源
      最近更新 更多