using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
{
private Button button1;
private Random random;
private Point[] positions;
public Form1()
{
InitializeComponent();
random = new Random();
button1 = new Button();
button1.Text = "Нажми меня!";
button1.Location = new Point(50, 50);
button1.Click += button1_Click;
Controls.Add(button1);
// Generate five random positions
positions = new Point[5];
for (int i = 0; i < 5; i++)
{
positions[i] = new Point(random.Next(ClientSize.Width - button1.Width),
random.Next(ClientSize.Height - button1.Height));
}
}
private void button1_Click(object sender, EventArgs e)
{
int index = random.Next(positions.Length);
button1.Location = positions[index];
}
}
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MoveButtonApp
{
public class MainForm : Form
{
private Button moveButton;
private Random random;
public MainForm()
{
this.Text = "Перемещающаяся кнопка";
this.Size = new Size(400, 300);
this.StartPosition = FormStartPosition.CenterScreen;
random = new Random();
moveButton = new Button();
moveButton.Text = "Нажми меня!";
moveButton.Size = new Size(100, 50);
moveButton.Location = new Point((this.ClientSize.Width - moveButton.Width) / 2,
(this.ClientSize.Height - moveButton.Height) / 2);
moveButton.Click += MoveButton_Click;
this.Controls.Add(moveButton);
this.Resize += MainForm_Resize;
}
private void MainForm_Resize(object sender, EventArgs e)
{
// Ensure the button stays within bounds when form is resized
var btn = moveButton;
if (btn.Left + btn.Width > this.ClientSize.Width)
btn.Left = this.ClientSize.Width - btn.Width;
if (btn.Top + btn.Height > this.ClientSize.Height)
btn.Top = this.ClientSize.Height - btn.Height;
}
private void MoveButton_Click(object sender, EventArgs e)
{
int maxX = this.ClientSize.Width - moveButton.Width;
int maxY = this.ClientSize.Height - moveButton.Height;
int newX = random.Next(0, maxX);
int newY = random.Next(0, maxY);
moveButton.Location = new Point(newX, newY);
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}