[ToolboxItem(true)] public class PictureBoxURL : PictureBox { private string _url = ""; public string ImageUrl { get { return _url; } set { _url = value; if (String.IsNullOrEmpty(_url)) return; GetImageByWebRequest(this, _url); } } public Image ImageLoading { get; set; } /// <summary> /// 推荐使用ByWebRequest /// </summary> /// <param name="edit"></param> /// <param name="url"></param> private void GetImageByWebClient(PictureBoxURL edit, string url) { WebClientImage tt = new WebClientImage(edit, url); Thread thread = new Thread(new ThreadStart(tt.Do)); thread.Start(); } private void GetImageByWebRequest(PictureBoxURL edit, string url) { WebRequestImage tt = new WebRequestImage(edit, url); Thread thread = new Thread(new ThreadStart(tt.Do)); thread.Start(); } public class WebClientImage { private PictureBoxURL edit; private string url; public WebClientImage(PictureBoxURL a, string b) { edit = a; url = b; } public void Do() { try { edit.BeginInvoke(new Action(() => { edit.Image = edit.ImageLoading; })); using (var client = new System.Net.WebClient()) { using (var strream = client.OpenRead(url)) { Image Image = new Bitmap(strream); edit.BeginInvoke(new Action(() => { edit.Image = Image; })); } } } catch { edit.BeginInvoke(new Action(() => { edit.Image = null; })); } } } private class WebRequestImage { private PictureBoxURL edit; private string url; public WebRequestImage(PictureBoxURL a, string b) { edit = a; url = b; } public void Do() { try { if (edit.IsHandleCreated) { edit.BeginInvoke(new Action(() => { edit.Image = edit.ImageLoading; })); } else edit.Image = edit.ImageLoading; var request = (HttpWebRequest)WebRequest.Create(url); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { using (var stream = response.GetResponseStream()) { Image Image = new Bitmap(stream);// Bitmap.FromStream(stream); edit.BeginInvoke(new Action(() => { edit.Image = Image; })); } } } } catch (Exception ex) { try { edit.BeginInvoke(new Action(() => { edit.Image = null; })); } catch { } } } } }