C# 以自己的 winform 程式開啟檔案(接收外部傳入參數)

開啟檔案時可以選擇用來開啟的程式,例如相簿、小畫家等。那如果想要點選檔案就使用自己寫的 winform 程式開啟該怎麼做?馬上開始詳細教學!

程式碼

首先先在 Program.cs 中增加 args 參數:
註:這時第 12 行的 args 應該會錯誤
	
namespace RuyutWinFormsAppExample;

static class Program
{
    /// 
    ///  The main entry point for the application.
    /// 
    [STAThread]
    static void Main(string[]? args)
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1(args));
    }
}

    

在 Form1.cs 裡面也增加 args 參數
	
namespace RuyutWinFormsAppExample;

public partial class Form1 : Form
{
    public Form1(string[]? args)
    {
		InitializeComponent();
    }
}
    

其實到這裡就結束了,啟動程式時讀取 args 參數並處理即可

說明

這個參數是什麼?如果執行本程式時有帶入參數,就會從這個 args 進來。我們加個彈出視窗來檢查看看
	
namespace RuyutWinFormsAppExample;

public partial class Form1 : Form
{
	public Form1(string[]? args)
   {
		InitializeComponent();
		if (args is not null && args.Length > 0) MessageBox.Show(string.Join("\n", args));
   }
}
    

如果直接開啟程式的話不會有任何反應,但是如果使用指令視窗開啟程式並傳入參數時資料就會進到 args 參數內:

.\RuyutWinFormsAppExample.exe aaa bbb ccc


註:RuyutWinFormsAppExample 為應用程式名稱
那和「使用應用程式開啟檔案」有什麼關聯?有的,因為實際上並不是「使用應用程式開啟檔案」,而是開啟應用程式然後「將檔案路徑作為參數傳入應用程式」
有點繞口,我們直接在 Sandbox 沙箱 測試看看
隨便找個檔案,使用滑鼠右鍵點擊,選擇「Open with...」

因為我們沒有註冊關聯,所以手動找到剛剛寫的應用程式路徑,點選「Open」

發現確實和我們使用指令並帶入參數一樣,args 有資料,並且確實是檔案路徑

那如果一次開啟多個檔案呢?將多個檔案選取直接拖曳到我們的應用程式上面,此時 args 有取得資料,並且確實是兩個檔案的路徑。
所以程式啟動時只要檢查 args 有內容就處理即可達成「使用 winform 開啟檔案」

既然都做到這裡了,那筆者就寫個小範例:使用自訂應用程式開啟圖片並顯示
完整程式碼:
Program.cs
	
namespace RuyutWinFormsAppExample;

static class Program
{
    /// 
    ///  The main entry point for the application.
    /// 
    [STAThread]
    static void Main(string[]? args)
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1(args));
    }
}

    

Form1.cs
	
using RuyutWinFormsAppExample.Properties;

namespace RuyutWinFormsAppExample;

public partial class Form1 : Form
{
    public Form1(string[]? args)
    {
        InitializeComponent();
        this.Text = "Ruyut WinForms App Example";

        if (args is not null && args.Length > 0 && File.Exists(args[0]))
        {
            this.Paint += (o, e) =>
            {
                using Graphics graphics = e.Graphics;
                using Image image = Image.FromFile(args[0]);
                graphics.DrawImage(image, 0, 0, image.Width, image.Height);
                this.Size = new Size(image.Width, image.Height);
            };
        }
    }
}
    

執行畫面:

留言