简体   繁体   English

以编程方式更改表单壁纸的不同方式

[英]Different way for programmatically change Form wallpaper

I need to programmatically assign form's wallpaper by a jpg file choosed by user. 我需要以编程方式通过用户选择的jpg文件分配表单的壁纸。 I've do this with new Bitmap but jpeg file become read only if I do so. 我用新的Bitmap做了这个,但是如果我这样做,jpeg文件就变成只读了。

It's possibile to load in RAM jpeg file and use it for wallpaper? 可以在RAM jpeg文件中加载并将其用于壁纸吗? Or add jpeg file to project resource and use resource? 或者将jpeg文件添加到项目资源并使用资源?

Sorry for my very very bad English :( 对不起我非常糟糕的英语:(

Best regards. 最好的祝福。

Use a MemoryStream : 使用MemoryStream

MemoryStream ms = new MemoryStream(File.ReadAllBytes(pathToImageFile));
this.BackgroundImage = Image.FromStream(ms); ;

The simplest way to avoid the file lock that GDI+ puts on the file is to make a deep copy of the bitmap with the Bitmap(Image) constructor. 避免GDI +放在文件上的文件锁定的最简单方法是使用Bitmap(Image)构造函数制作位图的深层副本。 Like this: 像这样:

    private void SetWallpaperButton_Click(object sender, EventArgs e) {
        if (openFileDialog1.ShowDialog() == DialogResult.OK) {
            using (var img = Image.FromFile(openFileDialog1.FileName)) {
                if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
                this.BackgroundImage = new Bitmap(img);
            }
        }
    }

The using statement ensures that the file lock gets released. using语句确保释放文件锁。 And the Dispose() call ensures that the old bitmap gets destroyed quickly, important because you are often skirting OOM with large bitmaps on a 32-bit operating system. 并且Dispose()调用确保旧位图被快速销毁,这很重要,因为您经常在32位操作系统上使用大位图来避开OOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM