C#怎么才能实现拖动控件时窗体也跟着移动 5
谁说不能拖动控件来移动窗体的。
这不就做出来了嘛:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace 可以拖动的工具箱 {
public partial class 工具箱窗体 : Form {
private Point 鼠标位置1, 鼠标位置2, 窗体位置1, 窗体位置2;
private bool 按下鼠标 = false;
public static bool 允许拖动 =true;
private void 工具箱窗体_MouseDown(object sender, MouseEventArgs e) {
if (允许拖动) {
if (e.Button == MouseButtons.Left) {
按下鼠标 = true;
// Save window position and mouse position
鼠标位置1 = Control.MousePosition;
窗体位置1 = Location;
}
}
}
private void 工具箱窗体_MouseMove(object sender, MouseEventArgs e) {
if (允许拖动 && 按下鼠标) {
//Get the current position of the mouse in the screen
鼠标位置2 = Control.MousePosition;
//Set window position
窗体位置2.X = 鼠标位置2.X - 鼠标位置1.X + 窗体位置1.X;
窗体位置2.Y = 鼠标位置2.Y - 鼠标位置1.Y + 窗体位置1.Y;
//Save window position
Location = 窗体位置2;
窗体位置1 = 窗体位置2;
//Save mouse position
鼠标位置1 = 鼠标位置2;
坐标显示.Visible = true;
var p = this.PointToScreen(this.Location);
var rect = this.RectangleToScreen(Form1.停靠面板.Bounds);
if (rect.Contains(p)) {
坐标显示.Location = new Point(e.X, e.Y - 坐标显示.Height);
坐标显示.BackColor = Color.DodgerBlue;
坐标显示.Text = string.Format("停靠");
} else {
坐标显示.Location = new Point(e.X, e.Y - 坐标显示.Height);
坐标显示.BackColor = Color.LightSeaGreen;
坐标显示.Text = string.Format("{0:0},{1:0}", p.X, p.Y);
}
}
}
private void 工具箱窗体_MouseUp(object sender, MouseEventArgs e) {
if (允许拖动) {
if (e.Button == MouseButtons.Left)
//Return back signal
按下鼠标 = false;
//判断是否位于停靠区域
var p = this.PointToScreen(this.Location);
var rect = this.RectangleToScreen(Form1.停靠面板.Bounds);
if (rect.Contains(p)) {
允许拖动 = false;
this.Hide();
Location = rect.Location;
Form1.停靠面板.Visible = true;
}
坐标显示.Visible = false;
}
}
public 工具箱窗体() {
InitializeComponent();
}
private void 工具箱窗体_Load(object sender, EventArgs e) {
FormBorderStyle = FormBorderStyle.Fixed3D;
this.ControlBox = false;
this.ShowIcon = false;
this.ShowInTaskbar = false;
坐标显示.Visible = false;
}
}
}