防止图像被覆盖以进行覆盖,因为它是动态加载为背景的

时间:2012-09-16 23:43:38

标签: c# image background overwrite blocked

编辑:另请参阅我关于此计划的旧帖子,以获取背景信息C# - Making a BackgroundImage update in real time while editing it in other programs

我创建了一个图像查看器,它将所选图像显示为“表单”的背景。

在我关闭程序之前,我加载的所有图像都被阻止被其他应用程序覆盖,例如图像操作Photoshop或GIMP等应用程序。

我的代码非常简单:

public partial class Form1:Form {
    private string FileName;

    public Form1() {
        InitializeComponent();

        FileName = "";
        openFileDialog1.Filter = "PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg";
    }

    private void button1_Click( object sender, EventArgs e ) {
        if(openFileDialog1.ShowDialog() == DialogResult.OK) {
            button2.Enabled = true;
            FileName = openFileDialog1.FileName;
            setImage();
        }
    }

    private void button2_Click( object sender, EventArgs e ) {
        setImage();
    }

    private void setImage() {
        Stream str=new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        Bitmap tempImg= new Bitmap( Bitmap.FromStream(str) );
        str.Close();
        using( tempImg = new Bitmap(FileName) ) {
            Rectangle rect = new Rectangle(0, 0, tempImg.Width, tempImg.Height);
            PixelFormat format = tempImg.PixelFormat;

            this.BackgroundImage = new Bitmap(FileName).Clone(rect, format);
        }
        openFileDialog1.FileName = "";
    }
}

我该如何解决这个问题?

更新:

此代码对我不起作用。

    private void setImage() {
        // using (FileStream stream = new FileStream("MyImage.png", FileMode.Open, FileAccess.Read))
        //var image = Image.FromStream(stream); 
        using( new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read) ) {
            Stream str=new FileStream( FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            Bitmap tempImg= new Bitmap( Bitmap.FromStream(str) );
            str.Close();
            tempImg = new Bitmap(FileName);
            Rectangle rect = new Rectangle(0, 0, tempImg.Width, tempImg.Height);
            PixelFormat format = tempImg.PixelFormat;

            this.BackgroundImage = new Bitmap(FileName).Clone(rect, format);
        }
        openFileDialog1.FileName = "";
    }

1 个答案:

答案 0 :(得分:0)

using (FileStream stream = new FileStream("MyImage.png", FileMode.Open, FileAccess.Read))
{
   var image = Image.FromStream(stream);

    // Do something with the image.
}

// The image will not be locked here.