我试图仅为IP摄像机制作观众。没什么大不了的,但我遇到了一个问题,其中Image被打开并加载到picturebox1
但它不会刷新,无论我是否将timer1
中的计时器设置为500(ms)
代码:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string url = "http://IPofIPCamera/now.jpg";
WebClient webClient = new WebClient();
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic",
new NetworkCredential("SomeUser", "SomePass"));
webClient.Credentials = myCache;
MemoryStream imgStream = new MemoryStream(webClient.DownloadData(url));
pictureBox1.Image = new System.Drawing.Bitmap(imgStream);
}
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Update();
}
}
使用此代码PictureBox1
是从网址加载的图片,但未刷新。
我做错了什么?
答案 0 :(得分:1)
所以,你对PictureBox.Update
的工作原理有误解,这被描述为here:
使控件重绘其客户区域内的无效区域。
这意味着不会再次触发下载。
要解决您的问题,您应该提取一个下载和设置图像的方法,该方法将由计时器的勾号触发。
public void DownloadAndUpdatePicture()
{
string url = "http://IPofIPCamera/now.jpg";
WebClient webClient = new WebClient();
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential("SomeUser", "SomePass"));
webClient.Credentials = myCache;
MemoryStream imgStream = new MemoryStream(webClient.DownloadData(url));
pictureBox1.Image = new System.Drawing.Bitmap(imgStream);
}
private void Form1_Load(object sender, EventArgs e)
{
this.DownloadAndUpdatePicture();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.DownloadAndUpdatePicture();
}