提交 189f8e18 编写于 作者: 林新发's avatar 林新发

winform download demo

上级 ec675614

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29613.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "winform1", "winform1\winform1.csproj", "{8B81BC07-122C-4F8A-8710-851A7105B480}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8B81BC07-122C-4F8A-8710-851A7105B480}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8B81BC07-122C-4F8A-8710-851A7105B480}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8B81BC07-122C-4F8A-8710-851A7105B480}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8B81BC07-122C-4F8A-8710-851A7105B480}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {700158E2-F1AA-45B3-B735-D12B257B85C0}
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
\ No newline at end of file
using System;
using System.IO;
using System.Net;
namespace winform1
{
class DownloadThread
{
/// <summary>
/// 线程开始事件
/// </summary>
public event EventHandler threadStartEvent;
/// <summary>
/// 线程执行时事件
/// </summary>
public event EventHandler threadEvent;
/// <summary>
/// 线程结束事件
/// </summary>
public event EventHandler threadEndEvent;
/// <summary>
/// c#,.net 下载文件
/// </summary>
/// <param name="url">下载文件地址</param>
/// <param name="filename">下载后的存放地址</param>
public void RunMethod(string url, string filename)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//通知主界面,我开始了, response.ContentLength用来设置进度条的最大值
threadStartEvent.Invoke(response.ContentLength, null);
Stream st = response.GetResponseStream();
Stream so = new FileStream(filename, FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, by.Length);
while (osize > 0)
{
totalDownloadedByte += osize;
so.Write(by, 0, osize);
osize = st.Read(by, 0, by.Length);
//通知主界面我正在执行,totalDownloadedByte表示进度条当前进度
threadEvent.Invoke(totalDownloadedByte, null);
}
so.Close();
st.Close();
//通知主界面我已经完成了
threadEndEvent.Invoke(null, null);
}
catch (Exception)
{
throw;
}
}
}
}
namespace winform1
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.pictureBg = new System.Windows.Forms.PictureBox();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.tipsLbl = new System.Windows.Forms.Label();
this.processLbl = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBg)).BeginInit();
this.SuspendLayout();
//
// pictureBg
//
this.pictureBg.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBg.Image = ((System.Drawing.Image)(resources.GetObject("pictureBg.Image")));
this.pictureBg.Location = new System.Drawing.Point(0, 0);
this.pictureBg.Margin = new System.Windows.Forms.Padding(4);
this.pictureBg.Name = "pictureBg";
this.pictureBg.Size = new System.Drawing.Size(1001, 530);
this.pictureBg.TabIndex = 0;
this.pictureBg.TabStop = false;
//
// progressBar
//
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar.BackColor = System.Drawing.SystemColors.Control;
this.progressBar.Location = new System.Drawing.Point(0, 520);
this.progressBar.Margin = new System.Windows.Forms.Padding(4);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(1001, 10);
this.progressBar.TabIndex = 1;
//
// tipsLbl
//
this.tipsLbl.AutoSize = true;
this.tipsLbl.BackColor = System.Drawing.Color.Transparent;
this.tipsLbl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.tipsLbl.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.tipsLbl.ForeColor = System.Drawing.Color.Black;
this.tipsLbl.Location = new System.Drawing.Point(352, 498);
this.tipsLbl.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.tipsLbl.Name = "tipsLbl";
this.tipsLbl.Size = new System.Drawing.Size(174, 20);
this.tipsLbl.TabIndex = 2;
this.tipsLbl.Text = "正在下载中,请耐心等待";
//
// processLbl
//
this.processLbl.AutoSize = true;
this.processLbl.BackColor = System.Drawing.Color.Transparent;
this.processLbl.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.processLbl.Location = new System.Drawing.Point(538, 498);
this.processLbl.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.processLbl.Name = "processLbl";
this.processLbl.Size = new System.Drawing.Size(40, 20);
this.processLbl.TabIndex = 3;
this.processLbl.Text = "00%";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1001, 530);
this.Controls.Add(this.processLbl);
this.Controls.Add(this.tipsLbl);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.pictureBg);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBg)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBg;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.Label tipsLbl;
private System.Windows.Forms.Label processLbl;
}
}
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Ionic.Zip;
namespace winform1
{
public partial class Form1 : Form
{
private Point m_mousePos;
private bool m_isMouseDown;
//要下载的文件的url
private const string m_url = "https://codechina.csdn.net/linxinfa/fontmaker/-/raw/master/FontCreator.zip";
//下载到本地的文件名
private const string m_saveFile = "./download.zip";
//加压目录
private const string m_unzipFile = "./unzip";
public Form1()
{
InitializeComponent();
InitUi();
StartDownload();
}
private void InitUi()
{
//隐藏标题栏
this.FormBorderStyle = FormBorderStyle.None;
//背景图
pictureBg.SizeMode = PictureBoxSizeMode.StretchImage;
//窗口移动控制
pictureBg.MouseDown += OnMouseDown;
pictureBg.MouseUp += OnMouseUp;
pictureBg.MouseMove += OnMouseMove;
progressBar.MouseDown += OnMouseDown;
progressBar.MouseUp += OnMouseUp;
progressBar.MouseMove += OnMouseMove;
//提示语
tipsLbl.Parent = pictureBg;
processLbl.Parent = pictureBg;
processLbl.Text = "0%";
//进度条
progressBar.Minimum = 0;
progressBar.Maximum = 100;
}
#region 隐藏标题栏后支持移动窗口
/// <summary>
/// 鼠标按下,开启移动
/// </summary>
/// <param name="e"></param>
protected void OnMouseDown(object sender, MouseEventArgs e)
{
m_mousePos = Cursor.Position;
m_isMouseDown = true;
}
/// <summary>
/// 鼠标抬起,关闭移动
/// </summary>
/// <param name="e"></param>
protected void OnMouseUp(object sender, MouseEventArgs e)
{
m_isMouseDown = false;
this.Focus();
}
/// <summary>
/// 移动窗口
/// </summary>
/// <param name="e"></param>
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (m_isMouseDown)
{
Point tempPos = Cursor.Position;
this.Location = new Point(Location.X + (tempPos.X - m_mousePos.X), Location.Y + (tempPos.Y - m_mousePos.Y));
m_mousePos = Cursor.Position;
}
}
#endregion
#region 更新进度条
/// <summary>
/// 被委托调用,专门设置进度条最大值
/// </summary>
/// <param name="maxValue"></param>
public void SetMax(int maxValue)
{
progressBar.Maximum = maxValue;
}
/// <summary>
/// 被委托调用,专门设置进度条当前值
/// </summary>
/// <param name="nowValue"></param>
private void SetNow(int nowValue)
{
progressBar.Value = nowValue;
string nowValueStr = string.Format("{0:F}", (float)nowValue / this.progressBar.Maximum * 100);
processLbl.Text = nowValueStr + "%";
}
#endregion
private void StartDownload()
{
DownloadThread method = new DownloadThread();
//先订阅一下事件
method.threadStartEvent += new EventHandler(DownloadThreadStartEvent);
method.threadEvent += new EventHandler(DownloadThreadIngEvent);
method.threadEndEvent += new EventHandler(DownloadThreadEndEvent);
//开启一个线程进行下载
Task task = new Task(() => { method.RunMethod(m_url, m_saveFile); });
task.Start();
}
private void UnZipFile(string file)
{
using (ZipFile zip = new ZipFile(file))
{
zip.ExtractAll(m_unzipFile);
}
}
/// <summary>
/// 线程开始事件,设置进度条最大值
/// 但是我不能直接操作进度条,需要一个委托来替我完成
/// </summary>
/// <param name="sender">ThreadMethod函数中传过来的最大值</param>
/// <param name="e"></param>
void DownloadThreadStartEvent(object sender, EventArgs e)
{
int maxValue = Convert.ToInt32(sender);
Invoke(new Action<int>(SetMax), maxValue);
}
/// <summary>
/// 线程执行中的事件,设置进度条当前进度
/// 但是我不能直接操作进度条,需要一个委托来替我完成
/// </summary>
/// <param name="sender">ThreadMethod函数中传过来的当前值</param>
/// <param name="e"></param>
void DownloadThreadIngEvent(object sender, EventArgs e)
{
int nowValue = Convert.ToInt32(sender);
Invoke(new Action<int>(SetNow), nowValue);
}
/// <summary>
/// 线程完成事件
/// </summary>
void DownloadThreadEndEvent(object sender, EventArgs e)
{
MessageBox.Show("下载完成完成,点击确定执行解压");
UnZipFile(m_saveFile);
}
}
}
此差异已折叠。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace winform1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("winform1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("winform1")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("8b81bc07-122c-4f8a-8710-851a7105b480")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace winform1.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("winform1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>