Home > Programming > [WPF] アプリケーションの実行パスを取得する

[WPF] アプリケーションの実行パスを取得する

小ネタ。

WPF の Application クラスには、System.Windows.Forms.Application クラスほど便利ではなく、たとえば StartupPath プロパティがない。ないなら作れ、って感じなのだけど、はてさて。

public string GetStartupPath()
{
	System.IO.Path.GetDirectoryName(
		Environment.GetCommandLineArgs()[0]);
}

Environment.GetCommandLine はコマンドライン引数を返してくれるが、その先頭には必ずアプリケーションの実行パスが含まれている。それを利用しよう。つまり、コマンドライン引数を string 配列にして返してくれる Environment.GetCommandLineArgs()[0] がすなわちそのまま EXE のパスになっている。

ほかにも、System.Windows.Forms.Application にはいろいろ便利なプロパティや関数があるので、それをマネして WPF の App クラス(プロジェクト作成時に自動生成されるヤツ)のプロパティとして実装しておけば、いろいろと便利かもしれない。

こんなの何に使うんだって?タスクトレイアイコンのあるWPFアプリなんかで役立つかなぁ…。たとえば、アプリのアイコンを取得してそのままタスクトレイアイコンにしてしまう例。

private System.Windows.Forms.NotifyIcon ni;

public Window1()
{
    InitializeComponent();

	ni =  = new System.Windows.Forms.NotifyIcon();
    ni.Icon = System.Drawing.Icon.ExtractAssociatedIcon(
        Environment.GetCommandLineArgs()[0]);
    ni.Visible = false;
    ni.Text = App.Current.MainWindow.Title;
    ni.DoubleClick +=
        delegate(object sender, EventArgs args)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
        };
}
blog comments powered by Disqus

Home > Programming > [WPF] アプリケーションの実行パスを取得する

My Friend Feed

http://friendfeed.com/daruyanagi

Google Analyticator

790
 Unique Visitors 
 (1 day) 
Powered By Google Analytics

Return to page top