C#:将文件拖放到 .exe(图标)上并获取文件路径
C#: Drag & Drop File on .exe (icon) and get filepath
我是 C# 新手,无法解决这个问题。这就是我想要实现的目标。
每当我将文件拖放到 .exe 文件上(在图标本身上)时,应用程序应捕获拖动文件的文件路径。
谢谢。
如果我没理解错的话,您想将文件拖放到 exe 的图标上,而不是应用程序本身。如果是这样,可以使用传递给应用程序的参数轻松实现。如果您在制作控制台应用程序时检查原始样板代码,它具有应用程序入口点:
static void Main(string[] args)
如果将文件拖放到应用程序的图标上,args[0] 将保存被拖放文件的名称。如果目标是将文件拖放到 EXE 文件中,那么有很多关于 SO 的教程。
如果您编写以下代码,那么当您将文件拖到 exe 图标上时,args[0] 将保存它的路径作为参数:
(我添加了 if 语句,如果你启动程序而不拖任何东西
它不应该崩溃)
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args[0]);
}
Console.ReadLine();
}
}
通过将默认 string[] args
添加到 Program
中的 Main
函数,我能够将拖放添加到使用 Windows 表单创建的 executable/shortcut =].然后,将相同的参数添加到 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...
}
}
我是 C# 新手,无法解决这个问题。这就是我想要实现的目标。 每当我将文件拖放到 .exe 文件上(在图标本身上)时,应用程序应捕获拖动文件的文件路径。
谢谢。
如果我没理解错的话,您想将文件拖放到 exe 的图标上,而不是应用程序本身。如果是这样,可以使用传递给应用程序的参数轻松实现。如果您在制作控制台应用程序时检查原始样板代码,它具有应用程序入口点:
static void Main(string[] args)
如果将文件拖放到应用程序的图标上,args[0] 将保存被拖放文件的名称。如果目标是将文件拖放到 EXE 文件中,那么有很多关于 SO 的教程。
如果您编写以下代码,那么当您将文件拖到 exe 图标上时,args[0] 将保存它的路径作为参数: (我添加了 if 语句,如果你启动程序而不拖任何东西 它不应该崩溃)
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args[0]);
}
Console.ReadLine();
}
}
通过将默认 string[] args
添加到 Program
中的 Main
函数,我能够将拖放添加到使用 Windows 表单创建的 executable/shortcut =].然后,将相同的参数添加到 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...
}
}