我想以编程方式将图像放入不活动的表单中。
Image myImage = new Image();
gfx = Form.ActiveForm.CreateGraphics();
gfx.DrawImage(myImage, 0,0);
只有在表单处于事件状态时它才会完美地工作,但是当表单处于非事件状态时它就没有意义了,只会返回一个错误:
In an instance of an object reference not set to an object.
如何处理我的应用程序中未激活的表单并为其添加图片?
更新 1
我做了实例,并打开了 DoubleBuffered 属性(true)但没有任何反应:
Form1 form = new Form1();
gfx = form.CreateGraphics();
gfx.DrawImage(bmp, 0, 0);
upd 2 More Source,是我加的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
namespace testimg
{
class doimg
{
public void picture()
{
// some staffs to get a picture, so it's in bmp object now.
gfx = this. // watch picture below
gfx.DrawImage(bmp, 0, 0);
// I tried to use PictureBox, but it's the same issue (I can't handle it on a form)
PictureBox pb = new PictureBox();
pb.CreateGraphics();
pb.DrawToBitmap(bmp,pb.ClientRectangle);
}
}
}
Arif Eqbal 解的图片:no graph methods for this (pic)
更新 3
我所拥有的完整资源(计时器为 10 秒)
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
doimg pic = new doimg();
pic.picture();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
}
doimg.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
namespace testimg
{
class doimg
{
public void picture()
{
// some staffs to get a picture, so it's in bmp object now.
Bitmap bmp = new Bitmap(200, 200, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics gfx = Graphics.FromImage(bmp);
gfx = Form1.ActiveForm.CreateGraphics(); // works well with active form
gfx.DrawImage(bmp, 0, 0);
}
}
}
和项目的整个文件 http://www.filedropper.com/testimg
如您所见,程序处于事件状态时一切运行良好。仍然需要帮助。
最佳答案
在您的 Form2 上,尝试这样设置:
public partial class Form2 : Form {
public Image MyImage { get; set; }
public Form2() {
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e) {
if (MyImage != null) {
e.Graphics.DrawImage(MyImage, 0, 0);
}
base.OnPaint(e);
}
}
然后从你的事件表单中,你可以调用另一个表单来绘制它自己:
public partial class Form1 : Form {
Form2 f2 = new Form2();
public Form1() {
InitializeComponent();
f2.Show();
}
private void button1_Click(object sender, EventArgs e) {
f2.MyImage = myImage;
f2.Invalidate();
}
}
关于c# - 以编程方式将图像放入不活动的表单中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661223/