拖動控件
阿新 • • 發佈:2019-03-02
one control component 光標坐標 public mes 工作 eve handle {
CurX = e.X;
CurY = e.Y;
Mousedown = true;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.Arrow;
}
}
private void Controls_MouseMove(object sender, MouseEventArgs e)
{
if (Mousedown)
{
// 獲取當前屏幕的光標坐標
Point pTemp = new Point(Cursor.Position.X, Cursor.Position.Y);
// 轉換成工作區坐標
pTemp = this.PointToClient(pTemp);
// 定位事件源的 Location
Control control = sender as Control;
control.Location = new Point(pTemp.X - CurX, pTemp.Y - CurY);
}
}
private void Controls_MouseUp(object sender, MouseEventArgs e)
{
Mousedown = false;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.IBeam;
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.MouseDown += new MouseEventHandler(Controls_MouseDown);
button1.MouseMove += new MouseEventHandler(Controls_MouseMove);
button1.MouseUp += new MouseEventHandler(Controls_MouseUp);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("ddd");
}
}
public partial class Form1 : Form
{
private bool Mousedown;
/// <summary>
/// 鼠標在事件源的位置
/// </summary>
private int CurX = 0;
private int CurY = 0;
public Form1()
{
InitializeComponent();
}
private void Controls_MouseDown(object sender, MouseEventArgs e)
CurX = e.X;
CurY = e.Y;
Mousedown = true;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.Arrow;
}
}
private void Controls_MouseMove(object sender, MouseEventArgs e)
{
if (Mousedown)
// 獲取當前屏幕的光標坐標
Point pTemp = new Point(Cursor.Position.X, Cursor.Position.Y);
// 轉換成工作區坐標
pTemp = this.PointToClient(pTemp);
// 定位事件源的 Location
Control control = sender as Control;
control.Location = new Point(pTemp.X - CurX, pTemp.Y - CurY);
}
private void Controls_MouseUp(object sender, MouseEventArgs e)
{
Mousedown = false;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.IBeam;
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.MouseDown += new MouseEventHandler(Controls_MouseDown);
button1.MouseMove += new MouseEventHandler(Controls_MouseMove);
button1.MouseUp += new MouseEventHandler(Controls_MouseUp);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("ddd");
}
}
拖動控件