2013-04-06 45 views

回答

4

假設你的PictureBox具有100x100像素尺寸。 timer1應該啓用

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 WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public Random r = new Random(); 
     private void timer1_Tick(object sender, EventArgs e) 
     { 
      int x = r.Next(0,925); 
      int y = r.Next(0,445); 
      pictureBox1.Top = y; 
      pictureBox1.Left = x; 
     } 
    } 
} 
+0

謝謝:)工作得很好 – 2013-04-06 15:56:11

1

嘗試這樣:

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      tm.Interval = 100; 
      tm.Tick += new EventHandler(tm_Tick); 
      tm.Start(); 
     } 
     Timer tm = new Timer(); 
     void tm_Tick(object sender, EventArgs e) 
     { 
      pictureBox1.Location = new Point((int)(new Random().Next(0, 1025)), (int)(new Random().Next(0, 545))); 
     } 

    } 

編輯:您還必須檢查你的圖片是境內或境外的形式:

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      tm.Interval = 1000; 
      tm.Tick += new EventHandler(tm_Tick); 
      tm.Start(); 
     } 
     Timer tm = new Timer(); 
     int X = 0; 
     int Y = 0; 
     void tm_Tick(object sender, EventArgs e) 
     { 
      X = ((int)(new Random().Next(0, 1025))); 
      Y = ((int)(new Random().Next(0, 545))); 
      if (X > 1025 - pictureBox1.Width) 
      { 
       X = 1025 - pictureBox1.Width; 
      } 
      if (Y > 545 - pictureBox1.Height) 
      { 
       Y = 545 - pictureBox1.Height; 
      } 
      pictureBox1.Location = new Point(X, Y); 
     } 

    } 
+0

@HugoLöwgren:看我的編輯 – KF2 2013-04-06 15:49:37