2012年11月19日月曜日

コマンドライン引数を取得するプログラム

コマンドライン引数を取得する方法を確認するため、作ってみた。

起動すると

ラベル1に System.Environment.CommandLine の値
       フルパスでファイル名と引数

ラベル2に 配列に格納された System.Environment.GetCommandLineArgs() の値
       配列[0] には、フルパスでファイル名、引数が指定されていない場合も有効

ラベル3に 配列からデータを得るための値

が表示される。


ボタンをクリックすると、
配列からデータを得るための値を増やし、ラベル2とラベル3が変更される。
       配列[1]  以降が指定した引数となる。


配列のデータ数確認は、 配列名.Length
引数が指定されていない場合が 1、引数が2つあれば 3 となる。



デバッグ中に引数を指定する方法は、[プロジェクト名] のプロパティ (Alt+F7) の
デバッグ - コマンドライン引数 の欄に指定できる。



Command line arguments WinDesktop C# のプログラム

Form に button と label を3つ配置


Form1.cs
=======================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Command_line_arguments
{
    public partial class Form1 : Form
    {
        // 引数を配列に格納
        string[] args = System.Environment.GetCommandLineArgs();
        int i = 0;      
        
        public Form1()
        {
            InitializeComponent();
            // フルパスでファイル名と引数を表示
            this.label1.Text = System.Environment.CommandLine;
            // 配列[0] には、フルパスでファイル名
            this.label2.Text = args[i];
            this.label3.Text = "変数 i の値 : " + i.ToString();
            // this.label3.Text = args.Length.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 配列のデータ数確認、引数がなくてもデータ数は1
            // i = i + 1;
            if (args.Length > ++i)
            {
                // 配列[1] からが引数
                this.label2.Text = args[i];
                this.label3.Text = "変数 i の値 : " + i.ToString();
                // Clipboard.SetText(args[i]);
            }
        }
    }
}

=======================================================================


0 件のコメント:

コメントを投稿