后台不更新c#

本文关键字:更新 后台 | 更新日期: 2023-09-27 17:54:37

我在学习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;
        }

任何建议,为什么我的形式不显示更新的背景?

谢谢。

后台不更新c#

我复制了您的场景,并将this.Invalidate()替换为this.Refresh(),它工作了。这是在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));                
        }
    }