Home > C# > Visual C# Note: Open a File in Your Own Program When Double Clicking the File

Visual C# Note: Open a File in Your Own Program When Double Clicking the File

Suppose you want to open *.cwd files in your own program when you double click them. Here is how to do it:

  1. First of all, you need to make sure your program understands the structure of *.cwd files and knows how to open them.
  2. Set your program to be the default application to open *.cwd files. This is done by following these easy steps:
    1. Right click a .cwd file.
    2. Select “Open With” -> “Choose Program …”
    3. In the “Open With” dialog, check “Always use the selected program to open this kind of file” and press “Browse…”
    4. Find your application in the open file dialog and click “OK”.

    These way when you double click a .cwd file, the default action will be openning it with your application.

  3. Add a constructor in your main window form class. This constructor takes one parameter (the file name) from the Main(string[] args) function and open the file in your program.

Here is an example code that shows how to open *.cwd files in your C# application:

Program.cs:
 
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
 
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (args.Length > 0)
                Application.Run(new Form1(args[0]));
            else
                Application.Run(new Form1());
        }
    }
Form1.cs:
 
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        public Form1(string filename)
        {
            InitializeComponent();
            if (filename != null)
                LoadFile(filename);
        }
 
        private void LoadFile(string filename)
        {
            //
            // put your code here to load *.cwd file
           //
        }
    }
Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.