2011-02-02 11 views
12

PictureBoxを使用して、C#でイメージを表示したいとします。私は、コントリビュータがpictureBoxのタイマーとタイマーを作成しました。そこからオブジェクトを作成するときは、何も表示されません。イメージをC言語で表示する#

どうすればよいですか?

私はtimer1を正しく使用していますか? Timerが有効になっていることを

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

    } 

答えて

11

Formに画像ボックスを追加する必要があります。方法はForm.Controls.Add()です。

2

チェック:

は、ここに私のコードです。 Start()メソッドを呼び出す前に、timer1.Enabled = true;を実行する必要があります。

5

あなたのピクチャボックスが現在のフォームに追加されていないためです。

あなたはForm.Controlsプロパティを持っていますが、それはAdd()メソッドを持っています。

+0

私はそれをどこに置くべきですか? move_create()メソッドでForm1.Controls.Add(p)を書きましたが、エラーが発生しました... –

+0

フォームへの参照が必要です。あなたのクラスのコンストラクタにプロパティを渡して渡してください。 – Shimrod

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!! 
    } 
} 
+1

+1これは状況の良い習慣であり、タイマー付きのコントロールに不可欠なdisposeメソッドがないだけです。 – honibis

関連する問題