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

using System.Net;

namespace Ex09_7
{
    public partial class Form1 : Form
    {
        private WebClient m_objClient;

        public Form1()
        {
            InitializeComponent();
            m_objClient = new WebClient();
            m_objClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(m_objClient_DownloadProgressChanged);
            m_objClient.DownloadFileCompleted += new AsyncCompletedEventHandler(m_objClient_DownloadFileCompleted);
        }

        void m_objClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            label7 .Text  = Convert.ToString(e.TotalBytesToReceive);
            label6 .Text = Convert.ToString(e.BytesReceived);
            progressBar1.Value = e.ProgressPercentage;
        }

        void m_objClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("发生错误：" + e.Error.Message);
                return;
            }
            if (e.Cancelled)
                 MessageBox.Show(this, "下载已被取消！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(this, "下载已完成！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (m_objClient.IsBusy)
            {
                MessageBox.Show("WebClient繁忙");
                return;
            }
            string sURL = textBox1.Text.Trim();
            string sPath = textBox2.Text.Trim();
            if (sURL.Length <= 0)
            {
                MessageBox.Show("请输入所要下载文件的URL.");
                textBox1.Focus();
                return;
            }
            if (sPath.Length <= 0)
            {
                MessageBox.Show("请设置下载文件的保存路径.");
                textBox2.Focus();
                return;
            }
            m_objClient.DownloadFileAsync(new Uri(sURL), sPath);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult ret = saveFileDialog1.ShowDialog();
            if (ret == DialogResult.OK)
            {
                textBox2 .Text  = saveFileDialog1.FileName;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (m_objClient.IsBusy)
            {
                if (MessageBox.Show(null, "WebClient繁忙，确定要关闭吗？", "关闭", MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question) == DialogResult.OK)
                    this.Close();
            }
            else
            {
                this.Close();
            }
        }
    }
}
