Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display an image in c#

Tags:

c#

winforms

I want to display images with c# with PictureBox . I've created an class that contians a pictureBox and a timer. but when create object from that nothing display.

what should i do?

am I using timer1 correctly?

Here is my code:

    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.
         ...

    }
like image 242
ha.M.ed Avatar asked Feb 02 '11 13:02

ha.M.ed


4 Answers

You need to add the picture box to a Form. Check out the Form.Controls.Add() method.

like image 152
Daren Thomas Avatar answered Sep 27 '22 20:09

Daren Thomas


It's because your pictureboxes are not added to the current form.

You have a Form.Controls property, which has a Add() method.

like image 20
Shimrod Avatar answered Sep 27 '22 19:09

Shimrod


Check that the Timer is enabled. You might need to do timer1.Enabled = true; before you call the Start() method.

like image 45
Neil Knight Avatar answered Sep 27 '22 19:09

Neil Knight


First of all - you will have to add the pictureBox(es) to the form, if you want them to show up. Anyway - I would try/recommend to create a userControl. Add a PictureBox to your new control, and a 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 
    }
}

Add this new Control to the forms.controls collection and that's it!

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!!
    }
}
like image 20
Pilgerstorfer Franz Avatar answered Sep 27 '22 21:09

Pilgerstorfer Franz