编辑:另请参阅我关于此程序的较早帖子以获取背景信息C# - 在其他程序中编辑时实时更新 BackgroundImage
我创建了一个图像查看器,它将所选图像显示为“表单”的背景。
在我关闭程序之前,我加载的所有图像都不会被其他应用程序覆盖,例如 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 = "";
}