关于C#,我遇到了一些问题。
我正在尝试通过下载用户指定的图像来动态更新表单的背景。
我下载图片的代码(并更新表单)如下所示:
public bool getImgFromWeb(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url, UriKind.Absolute));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//if response is okay, and it's an image
//sometimes 404 will be okay, but will redirect to website.
if ((response.StatusCode == HttpStatusCode.OK) &&
(response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)))
{
Bitmap tempImg = new Bitmap(response.GetResponseStream());
this.BackgroundImage = tempImg; //this line does nothing.
this.Invalidate(); //to force the window to redraw
}
else
{
MessageBox.Show("Sorry, the image your are trying to download does not exist. Please re-enter the image URL.");
return false;
}
}
catch (Exception ex)
{
MessageBox.Show("Sorry, an error: " + ex.Message + " occurred.");
return false;
}
有关为何我的表单没有显示更新背景的任何建议?
感谢。
答案 0 :(得分:1)
我复制了你的场景并用this.Refresh()替换了.Invalidate()并且它有效。这是在Visual Studio 2012中。
private void SetImageAsBackground(string uri)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
Bitmap temp = new Bitmap(response.GetResponseStream());
this.BackgroundImage = temp;
this.Refresh();
}
else
{
MessageBox.Show("This isn't an image!");
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Exception: {0}", ex));
}
}