我想以编程方式将图像放入不活动的表单中。
Image myImage = new Image();
gfx = Form.ActiveForm.CreateGraphics();
gfx.DrawImage(myImage, 0,0);
只有当表单处于活动状态时它才会完美地工作,但是当表单不活动时它是没有意义的,只是返回一个错误:
在对象引用的实例中未设置为对象。
如何处理在我的应用程序中未激活的表单并为其添加图片?
更新 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解决方案的图片:没有用于此的图形方法(图片)
更新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的整个存档
正如您所看到的,在程序处于活动状态时一切运行良好。仍然需要帮助。