Как контролировать положение кнопки на форме - C#
Формулировка задачи:
моя первая програма на С(шарп), так что прошу не слишком критиковать...проблема в том что я не могу добится что б кнопка не у бигала за нижнию и правую границы текущей формы, как решить эту задачу?
Решение задачи: «Как контролировать положение кнопки на форме»
textual
Листинг программы
using System;
using System.Windows.Forms;
namespace button
{
public partial class MainForm : Form
{ //чтобы генерировал разные значения, то лучше его создать 1 раз.
readonly Random _random = new Random();
public MainForm()
{
InitializeComponent();
}
private void CalculatePosition(bool toSetNewPosition)
{
if (toSetNewPosition)
{
int das = _random.Next(0, 4);
switch (das)
{
case 0:
button1.Left = button1.Left + button1.Width;
break;
case 1:
button1.Left = button1.Left - button1.Width;
break;
case 2:
button1.Top = button1.Top + button1.Height;
break;
case 3:
button1.Top = button1.Top - button1.Height;
break;
}
}
if (button1.Left < 0)
button1.Left = 0;
if ((button1.Left + button1.Width) > ClientSize.Width)
button1.Left = ClientSize.Width - button1.Width;
if (button1.Top < 0)
button1.Top = 0;
if ((button1.Top + button1.Height) > ClientSize.Height)
button1.Top = ClientSize.Height - button1.Height;
if (button1.Right > ClientSize.Width)
button1.Left = ClientSize.Width - button1.Width;
if (button1.Bottom > ClientSize.Height)
button1.Top = ClientSize.Height - button1.Height;
}
private void Button_MouseMove(object sender, MouseEventArgs e)
{
CalculatePosition(true);
}
private void MainForm_Resize(object sender, EventArgs e)
{
CalculatePosition(false);
}
}
}