using System;
using System.Windows.Forms;
using System.Threading;

namespace HandGrep {
    // 行選択ダイアログクラス
    class Dialog : Form {
        ListBox list;
        public ListBox List {
            get { return list; }
            private set { list = value; }
        }
        public Dialog() {
            this.Width = 300; this.Height = 200;
            this.Text = "選択して×ボタンを押してください。";
            this.List = new ListBox();
            this.List.Dock = DockStyle.Fill;
            this.List.SelectionMode = SelectionMode.MultiExtended;
            this.Controls.Add(this.List);
        }
        public void AddLine(string line) {
            this.List.Items.Add(line);
        }
    }
    // メインクラス
    class Program {
        static object objLock;                  // 排他オブジェクト
        static AutoResetEvent evDialogLoad;     // ダイアログ初期化イベント
        static AutoResetEvent evDialogClose;    // ダイアログ終了イベント
        static Dialog dlg;                      // ダイアログ
        delegate void MyDelegate();
 
        static void Main(string[] args) {
            objLock = new object();
            evDialogLoad = new AutoResetEvent(false);
            evDialogClose = new AutoResetEvent(false);

            // ダイアログ作成
            dlg = new Dialog();
            dlg.Load += new EventHandler(       // ダイアログ初期化イベントハンドラ登録
                delegate(object o, EventArgs e) {
                    evDialogLoad.Set();
                });
            // ダイアログを別スレッドで表示
            new MyDelegate(
                delegate() {
                    dlg.ShowDialog();
                }
            ).BeginInvoke(new AsyncCallback(OnDialogClose), null);
            evDialogLoad.WaitOne();             // ダイアログの初期化待ち
            // 標準入力ループ
            string line;
            while ((line = Console.ReadLine()) != null) {
                // 標準入力から１行読み込み、ダイアログに追加
                dlg.Invoke(new MyDelegate(
                    delegate() {
                        lock (objLock) {
                            if (dlg == null) return;
                            dlg.AddLine(line);
                        }
                    }
                ));
            }
            evDialogClose.WaitOne();            // ダイアログの終了待ち
        }
        // ダイアログクローズ後のコールバック
        static void OnDialogClose(IAsyncResult result) {
            lock (objLock) {
                // 選択行を標準出力に書き込む
                foreach (string line in dlg.List.SelectedItems) {
                    Console.WriteLine(line);
                }
                dlg = null;
            }
            evDialogClose.Set();
        }
    }
}
