HeyCHのブログ

慢性疲労のへいちゃんです

【C#】進捗状況ダイアログを表示しよう

今回のコードは以前作ったWebBrowserの続きとして作っていきます。
heych.hatenablog.com

進捗状況ダイアログ

  • ソリューションエクスプローラーの「WebBrowser」を右クリックし、新規フォームを追加
    f:id:HeyCH:20200405000112p:plain
    フォームの追加
  • Windows フォームの追加
    f:id:HeyCH:20200405000422p:plain
    Windows フォーム
  • LabelとProgressbarを追加し、良い感じの大きさにする。
    f:id:HeyCH:20200405001014p:plain
    Form2
  • Form2のプロパティ「FormBorderStyle」を「FixedDialog」に設定
  • Form2のプロパティ「StartPosition」を「CenterParent」に設定
  • Form2のプロパティ「ControlBox」を「False」に設定
    f:id:HeyCH:20200405001752p:plain
    プロパティ変更
  • progressBar1のプロパティ「Style」を「Marquee」に設定
    f:id:HeyCH:20200405004517p:plain
    Marquee
  • コードの表示
    f:id:HeyCH:20200405002003p:plain
    コードの表示
  • Form2.csへコード追加
        public Form2() {
            InitializeComponent();
        }
        public string Title {
            get {
                return this.Text;
            }
            set {
                this.Text = value;
            }
        }
        public string Message {
            get {
                return label1.Text;
            }
            set {
                label1.Text = value;
            }
        }
  • Form1のWebBrowserへ「Navigating」イベント追加
    f:id:HeyCH:20200405003024p:plain
    webBrowser1_Navigating
  • Form1.csへコード追加
         Form2 progressbarDialog = new Form2();
        public Form1() {
            InitializeComponent();
            progressbarDialog.Title = "Navigating...";
            progressbarDialog.Message = "Navigat中です。しばらくお待ちください。";
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
            if (e.KeyChar == (char)Keys.Enter) {
                try {
                    webBrowser1.Navigate(textBox1.Text);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, ex.GetType().ToString());
                }
            }
        }
        private void button1_Click(object sender, EventArgs e) {
            if(webBrowser1.CanGoBack) webBrowser1.GoBack();
        }

        private void button2_Click(object sender, EventArgs e) {
            if (webBrowser1.CanGoForward) webBrowser1.GoForward();
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) {
            textBox1.Text = webBrowser1.Url.ToString();
            progressbarDialog.Hide();
        }

        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
            //JSか何かの影響でフォームが閉じない場合があるため
            //自分で制御できる部分でダイアログ表示するのが望ましい
            if (progressbarDialog != null) progressbarDialog.Hide();
            progressbarDialog.Show(this);
        }