/// <summary> /// Функция, возвращающая новое положение кнопки /// </summary> /// <param name="b">Объект класса ButtonWithSpeed.</param> /// <param name="newmp">Новое положение мыши в результате движения.</param> private Point ChangeLocation(ButtonWithSpeed b, Point newmp) { Point res = new Point(-100, -100); int x = newmp.X - b.button.Location.X; int y = newmp.Y - b.button.Location.Y; // Двигаться никуда не нужно if (x == 0 && y == 0) { return(res); } // Длина вектора double k = Math.Sqrt(x * x + y * y); int dx = (int)(5 * x / k); int dy = (int)(5 * y / k); int newx = b.button.Location.X - dx; int newy = b.button.Location.Y - dy; int n; // Если движение мыши приводит к достижению кнопкой границ формы, отталкиваем кнопку на значение h от края if (b.button.Location.X - dx < 0 || b.button.Location.X - dx > ClientSize.Width - b.button.Width) { n = dx < 0 ? -h : +h; newx = b.button.Location.X + dx + n; } if (b.button.Location.Y - dy < menuStrip1.Height || b.button.Location.Y - dy > ClientSize.Height - b.button.Height) { n = dy < 0 ? -h : +h; newy = b.button.Location.Y + dy + n; } res = new Point(newx, newy); // Усыпляем поток для реализации скорости движения Thread.Sleep(10 * b.Speed); return(res); }
/// <summary> /// Метод для передачи между формами значения скорости новой кнопки /// </summary> private void OnButtonAdded(object sender, AddButtonEventArgs e) { ButtonWithSpeed newbut = new ButtonWithSpeed(Convert.ToInt32(e.Param)); Controls.Add(newbut.button); butList.Add(newbut); flag = true; Task t = new Task(() => { while (flag) { if (point1 != lastMousePosition) { Point nmp = point1; Point resPoint = ChangeLocation(newbut, nmp); Invoke(new Action(() => { if (resPoint != new Point(-100, -100)) { newbut.button.Location = resPoint; } })); } } }); tasks.Add(t); t.Start(); }
/// <summary> /// Обработчик события загрузки формы. /// </summary> private void Form1_Load(object sender, EventArgs e) { lastClientSize = ClientSize; butList = new List <ButtonWithSpeed>(); ButtonWithSpeed firstbut = new ButtonWithSpeed(); butList.Add(firstbut); Controls.Add(firstbut.button); flag = true; Task t = new Task(() => { while (flag) { if (point1 != lastMousePosition) { Point nmp = point1; Point resPoint = ChangeLocation(firstbut, nmp); Invoke(new Action(() => { if (resPoint != new Point(-100, -100)) { firstbut.button.Location = resPoint; } })); } } }); tasks.Add(t); t.Start(); }