検索機能

「Search/Replace」メニューを設定します。
TAB キーの使用を許可し、4 TAB に設定します。
Command Line 起動をサポートします。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. 今回は、文字列の「検索/置き換え」機能をプログラムして Search/Replace メニューを設定します。
    また TAB キーの使用を許可し、4 TAB に設定します。
    また Command Line から起動できるようにします。
  2. KeySearch() メソッドをコーディングします。
    MyDialog から検索キーを取得して richTextBox1 を検索します。
    m_Kword は検索キーを格納する領域です。
    見つかった全てのテキストの色を変えて表示すると共に、その件数を MessageBox で知らせます。
    この後のページで Shift+F5, Shift+F6 で順番に位置付けるようにする予定です。
        string      m_Kword;        // 検索キー
    
        private void KeySearch(object sender, EventArgs e)
        {
            MyDialog Mydlg = new MyDialog();
            Mydlg.txtBox.Text = m_Kword;
            DialogResult dr = Mydlg.ShowDialog();
    
            if (dr == DialogResult.OK)
            {
                int cnt = 0;
                m_Kword = Mydlg.str;
                for (int pos = 0; ; )
                {
                    pos = richTextBox1.Find(m_Kword, pos, RichTextBoxFinds.None);
                    if (pos < 0) break;
                    richTextBox1.SelectionColor = Color.DarkMagenta;
                    cnt++;
                    pos++;
                }
                MessageBox.Show("検索件数: " + cnt);
                richTextBox1.Select(0, 0);
            }
        }
    
  3. Replace() メソッドをコーディングします。
    MyDialog から検索キーと置き換文字列を取得して richTextBox1 の文字列を置き換ます。
    richTextBox1 には便利な Replace() メソッドがあるので、これを使って一括処理します。
    置き換えた個々の位置は Shift+F5, Shift+F6 で位置付けることが出来ます。
        private void Replace(object sender, EventArgs e)
        {
            RepDialog Repdlg = new RepDialog();
            Repdlg.k_Box.Text = m_Kword;
            DialogResult dr = Repdlg.ShowDialog();
            if (dr == DialogResult.OK)
            {
                richTextBox1.Text = richTextBox1.Text.Replace(Repdlg.k_str, Repdlg.r_str);
                m_Kword = Repdlg.r_str;
                m_flag = true;
            }
        }
    
  4. 検索キーを設定する Dialog Class です。
    Form1.cs の FileClass の後にでも追加して下さい。
    Dialog Class の詳細は DialogText を参照して下さい。
        //★ Dialog Class
        class MyDialog : Form
        {
            public TextBox txtBox;
            public string str;         //取得KeyWord
    
            public MyDialog()
            {
                Text = "Dialog Text Input";
                MaximizeBox = false;
                MinimizeBox = false;
                ControlBox = false;
                ShowInTaskbar = false;
                FormBorderStyle = FormBorderStyle.FixedDialog;
    
                Width = 250;
                Height = 130;
    
                Button btnOK = new Button();
                btnOK.Text = "OK";
                btnOK.Location = new Point(30, ClientSize.Height - btnOK.Height - 5);
                btnOK.Parent = this;
                btnOK.TabIndex = 1;
                btnOK.Click += new EventHandler(btnOK_Click);
                btnOK.DialogResult = DialogResult.OK;
    
                Button btnCancel = new Button();
                btnCancel.Text = "Cancel";
                btnCancel.Location = new Point(ClientSize.Width - btnCancel.Width - 30,
                    ClientSize.Height - btnCancel.Height - 5);
                btnCancel.Parent = this;
                btnCancel.TabIndex = 2;
                btnCancel.DialogResult = DialogResult.Cancel;
    
                txtBox = new TextBox();
                txtBox.Parent = this;
                txtBox.Location = new Point(10, 10);
                txtBox.Width = ClientSize.Width - 20;
                txtBox.TabIndex = 0;
            }
    
            void btnOK_Click(object sender, EventArgs e)
            {   str = txtBox.Text;  }
        }
    
  5. 検索キーと置き換キーを設定する RepDialog Class です。
        class RepDialog : Form
        {
            public TextBox k_Box;
            public TextBox r_Box;
            public string k_str;         //KeyWord
            public string r_str;         //Replace
    
            public RepDialog()
            {
                Text = "Dialog Text Input";
                MaximizeBox = false;
                MinimizeBox = false;
                ControlBox = false;
                ShowInTaskbar = false;
                FormBorderStyle = FormBorderStyle.FixedDialog;
    
                Width = 250;
                Height = 130;
    
                Button btnOK = new Button();
                btnOK.Text = "OK";
                btnOK.Location = new Point(30, ClientSize.Height - btnOK.Height - 5);
                btnOK.Parent = this;
                btnOK.TabIndex = 2;
                btnOK.Click += new EventHandler(btnOK_Click);
                btnOK.DialogResult = DialogResult.OK;
    
                Button btnCancel = new Button();
                btnCancel.Text = "Cancel";
                btnCancel.Location = new Point(ClientSize.Width - btnCancel.Width - 30,
                    ClientSize.Height - btnCancel.Height - 5);
                btnCancel.Parent = this;
                btnCancel.TabIndex = 3;
                btnCancel.DialogResult = DialogResult.Cancel;
    
                k_Box = new TextBox();
                k_Box.Parent = this;
                k_Box.Location = new Point(10, 10);
                k_Box.Width = ClientSize.Width - 20;
                k_Box.TabIndex = 0;
                r_Box = new TextBox();
                r_Box.Parent = this;
                r_Box.Location = new Point(10, 36);
                r_Box.Width = ClientSize.Width - 20;
                r_Box.TabIndex = 1;
            }
    
            void btnOK_Click(object sender, EventArgs e)
            {
                k_str = k_Box.Text;
                r_str = r_Box.Text;
            }
        }
    

TAB キー

  1. TAB Code(TAB キー)を使えるように設定して、タブ幅を4文字に設定します。
    ソースプログラムファイルでは、4文字幅ぐらいが適当です。
    richTextBox1 のプロパティから AcceptsTab を True に切り替えて下さい。
    規定値では False に設定されていて、TAB キーは受け付けません。
  2. タブ幅の設定には Win32 API の SendMessage() を使います。
    下記のように入口名を宣言して下さい。
        // タブの幅を設定する SendMessage() を定義
        [System.Runtime.InteropServices.DllImport("User32.dll")]
        static extern IntPtr SendMessage(
            IntPtr hWnd, int msg, int wParam, int [] lParam);
    
  3. FormLoad から SendMessage を呼び出します。
        private void Form_Load(object sender, EventArgs e)
        {
            // 4 TAB に設定
            const int EM_SETTABSTOPS = 0x00CB;
            SendMessage(richTextBox1.Handle, EM_SETTABSTOPS, 1, new int[] {16});
        }
    
    これで TAB キーが使えるようになり、カラムが揃います。

Command Line

  1. Command Line からの起動を設定します。
    この設定を行うと、ドラッグ&ドロップや拡張子に関連付けてダブルクリックで起動出来るようになります。
    詳細は Command Line 引数 を参照して下さい。
  2. Command Line から呼び出す形式を次の3通りに定めます。
    引数が無いときは txtedit.exe を起動してから、メニュー操作でファイルをオープンします。
    text_code には "utf-8" や "shift_jis" などを指定します。
    プログラムのメニューに無いコードも指定することが可能で、実質的にほとんどのコードに対応します。
    コードの詳細は Encoding クラス を参照して下さい。
    txtedit.exe<br>    
    txtedit.exe file_name<br>    
    txtedit.exe file_name text_code<br>    
    
  3. Command Line の形式に合わせて、Main() 関数を修正します。
    Main() 関数は Program.cs で定義されています。
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            switch (args.Length)
            {   case 0:
                    Application.Run(new Form1());
                    break;
                case 1:     // ファイル名を指定
                    Application.Run(new Form1(args[0]));
                    break;
                case 2:     // ファイル名とコード
                    Application.Run(new Form1(args[0], args[1]));
                    break;
            }
        }
    
  4. Command Line の形式に合わせて class Form1 の Constructor を修正します。
        // Constructor
        public Form1()
        {
            FormInit(string.Empty, string.Empty);
        }
        public Form1(string tpath)
        {
            FormInit(tpath, string.Empty);
        }
        public Form1(string tpath, string tcode)
        {
            FormInit(tpath, tcode);
        }
        private void FormInit(string tpath, string tcode)
        {
            InitializeComponent();
            if (tpath == string.Empty) return;
            LoadFile(tpath, tcode);
        }
    

[Next Chapter ↓] Single File Editor
[Previous Chapter ↑] XML に保存

超初心者のプログラム入門(C# Frame Work)