Possible Duplicate:
C# Windows 'Open With >' Context menu behaviour
How do I do this? Like if I right click on a file and click open with, then my program how do I do stuff to that file :/.
I use the following code to pass the first argument (the one that contains the file name) to my gui application:
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(args.Length == 0 ? new Form1(string.Empty) : new Form1(args[0]));
}
}
I test to see if there is an argument. If not and a user starts your program without one then you may get an exception in any code that tries to use it.
This is a snippet from my Form1 that deals with the incoming file:
public Form1(string path) {
InitializeComponent();
if (path != string.Empty && Path.GetExtension(path).ToLower() != ".bgl") {
//Do whatever
} else {
MessageBox.Show("Dropped File is not Bgl File","File Type Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
path = string.Empty;
}
//.......
}
You will see that I am checking the extension sent in - my app only works with one extension type - .bgl - so if the user tries to open some other file extension then I stop them. In this case I am dealing with a dropped file. This code will also allow a user to drag a file over my executable (or related icon) and the program will execute wit hthat file
You might also consider creating a file association between your file extension and your program if you have not already. This in conjunction with the above will allow the user to double click on your file and have your application open it.
The path to the file being opened is passed as a command line argument to your application. You need to read that argument and open the file from that path.
There are two ways to do this:
The easiest way is to loop through the values of the args
array passed as the single parameter to the Main
method:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
The second way to do it is to use the Environment.GetCommandLineArgs
method. This is useful if you want to extract the arguments at some arbitrary point within your application, rather than inside of the Main
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With