Движущиеся PictureBox - C#
Формулировка задачи:
У меня есть класс создающий PictureBox и кнопка, добавляющая их на tabPage.
PictureBox должен отталкиваться от стенок tabPage по тику таймера...
Никак не могу сообразить, какой код.
Я написала в событии таймера:
Но PictureBox летают хаотично и не отталкиваются от стенок, улетают за пределы tabPage.
Есть какие-нибудь идеи??
foreach (PictureBox p in tabPage1.Controls) { p.Left += X; if (p.Left >= tabPage1.Width - 16) { X = -1; } if (p.Left <= 0) { X = 1; } p.Top += Y; if (p.Top >= tabPage1.Height - 16) { Y = -1; } if (p.Top <= 0) { Y = 1; } }
Решение задачи: «Движущиеся PictureBox»
textual
Листинг программы
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace pros { public class Program:Form { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Program()); } public class myPictureBox : PictureBox { public int X, Y; public myPictureBox(int X, int Y) { this.X = X; this.Y = Y; } } TabControl tabControl1 = new TabControl(); TabPage tabPage1 = new TabPage(); Random rnd = new Random(); Timer timer1 = new Timer(); myPictureBox[] PB; int W, H; Program() { tabControl1.Parent = this; tabControl1.Bounds = new Rectangle(0,0,this.Width-10 ,this.Height-30 ); tabPage1.Parent = tabControl1; tabPage1.Bounds = new Rectangle(0, 0, tabPage1.Width, tabPage1.Height); W = tabPage1.Width - 16; H = tabPage1.Height - 16; PB = new myPictureBox[5]; for (int i = 0; i < 5; i++) { int k=(rnd.Next(2)==0?-1:1); int l=(rnd.Next(2)==0?-1:1); PB[i] = new myPictureBox(k*10,l*10); PB[i].Parent = tabPage1; PB[i].BorderStyle = BorderStyle.Fixed3D; PB[i].Bounds = new Rectangle(rnd.Next(W), rnd.Next(H),16,16); } timer1.Enabled = true; timer1.Interval = 100; timer1.Start(); timer1.Tick +=new EventHandler(timer1_Tick); } private void timer1_Tick(object sender, EventArgs e) { foreach (myPictureBox p in tabPage1.Controls) { p.Left += p.X; if (p.Left >= tabPage1.Width - 16) { p.X = -10; } if (p.Left <= 0) { p.X = 10; } p.Top += p.Y; if (p.Top >= tabPage1.Height - 16) { p.Y = -10; } if (p.Top <= 0) { p.Y = 10; } } } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д