0

当涉及到 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;

        }

关于为什么我的表单没有显示更新的背景的任何建议?

谢谢。

4

1 回答 1

1

我复制了您的场景并用 this.Refresh() 替换了 this.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));                
        }
    }
于 2013-01-19T12:58:23.057 回答