Движение шара по форме - C#
Формулировка задачи:
Создайте приложение, в котором с помощью меню можно задать направление движения шара, который начинает двигаться при щелчке ЛКМ, а останавливается при щелчке на ПКМ. Если можно, с комментариями.
Решение задачи: «Движение шара по форме»
textual
Листинг программы
public class Program
{
[STAThread]
public static void Main(string[] args)
{
var form = new Form
{
Text = "Форма",
ClientSize = new Size(300, 200),
StartPosition = FormStartPosition.CenterScreen,
BackColor = Color.White
};
var circle = new Circle(Brushes.Green, 10);
circle.Location = new Point(0, 100);
form.Controls.Add(circle);
form.Load += delegate
{
int dx = 7;
var timer = new Timer { Interval = 30 };
timer.Tick += delegate
{
if (circle.Location.X + dx > form.ClientSize.Width - circle.ClientSize.Width
|| circle.Location.X + dx < 0)
{
dx = -dx;
}
circle.Location = new Point(circle.Location.X + dx, circle.Location.Y);
};
form.MouseUp += (sender, eventArgs) =>
{
switch (eventArgs.Button)
{
case MouseButtons.Left:
timer.Start();
break;
case MouseButtons.Right:
timer.Stop();
break;
}
};
};
Application.Run(form);
}
class Circle : Control
{
public Circle(Brush brush, int radius)
{
int diameter = 2 * radius;
ClientSize = new Size(diameter, diameter);
BackgroundImage = new Bitmap(ClientSize.Width, ClientSize.Height);
using (Graphics graphics = Graphics.FromImage(BackgroundImage))
{
graphics.Clear(Color.White);
graphics.FillEllipse(brush, 0, 0, diameter, diameter);
}
}
}