在c#中显示图像

时间:2011-02-02 13:06:11

标签: c# winforms

我希望使用带有PictureBox的c#显示图像。我创建了一个包含pictureBox和计时器的类。但是当从那个没有任何东西显示创建对象时。

我该怎么办?

我正确使用timer1吗?

这是我的代码:

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        c1 c = new c1();
        c.create_move(1);
    }

}

class c1 {

    PictureBox p = new PictureBox();
    Timer timer1 = new Timer();

    public void create_move(int i){

        p.ImageLocation = "1.png";
        p.Location = new Point(50, 50 + (i - 1) * 50);

        timer1.Start();
        timer1.Interval = 15;
        timer1.Tick += new EventHandler(timer_Tick);
    }


    private int k = 0;
    void timer_Tick(object sender, EventArgs e)
    {
         // some code. this part work outside the class c1 properly.
         ...

    }

4 个答案:

答案 0 :(得分:19)

您需要将图片框添加到Form。查看Form.Controls.Add()方法。

答案 1 :(得分:7)

这是因为您的图片框未添加到当前表单中。

您有一个Form.Controls属性,其中包含Add()方法。

答案 2 :(得分:2)

检查Timer是否已启用。在调用timer1.Enabled = true;方法之前,您可能需要Start()

答案 3 :(得分:2)

首先 - 如果您希望它们显示,您必须将pictureBox添加到表单中。无论如何 - 我会尝试/建议创建一个 userControl 。将 PictureBox 添加到新控件和 TimerControl

public partial class MovieControl : UserControl
{
    // PictureBox and Timer added in designer!

    public MovieControl()
    {
        InitializeComponent();
    }

    public void CreateMovie(int i)
    {
        pictureBox1.ImageLocation = "1.png";
        pictureBox1.Location = new Point(50, 50 + (i - 1) * 50);

        // set Interval BEFORE starting timer!
        timer1.Interval = 15;
        timer1.Start();
        timer1.Tick += new EventHandler(timer1_Tick);
    }

    void timer1_Tick(object sender, EventArgs e)
    {
        // some code. this part work outside 
    }
}

将这个新控件添加到forms.controls集合中,就是这样!

class Form1
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MovieControl mc = new MovieControl();
        mc.CreateMovie(1);
        this.Controls.Add(mc); /// VITAL!!
    }
}