想要在winform中用鼠标随意移动控件,只需要处理好控件的三个内置方法即可
(1).通过鼠标移动事件,来重新定位控件的位置
(2).通过鼠标按下事件,确定是否点击中有效控件,并将光标修改
1. Move_MouseMove
/// <summary>
/// 鼠标按下为true,放开为false
/// </summary>
private bool mousedown = false;
/// <summary>
/// 鼠标在事件源的位置,分别为x和y坐标
/// </summary>
private int currentx = 0;
private int currenty = 0;
private void Move_MouseDown(object sender, MouseEventArgs e)
{
currentx = e.X;
currenty = e.Y;
mousedown = true;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.Arrow;
}
}
2. Move_MouseUp
private void Move_MouseUp(object sender, MouseEventArgs e)
{
mousedown = false;
if (sender is TextBox)
{
((TextBox)sender).Cursor = Cursors.IBeam;
}
}
3. Move_MouseDown
private void Move_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 - currentx, pTemp.Y - currenty);
zlbllocation.Text = "坐标 x:" + (pTemp.X - currentx).ToString() + " y:" + (pTemp.Y - currenty).ToString();
}
}
可以将当前结果转成图片
private void zlblsave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.FileName = "img" + DateTime.Now.ToString("yyyymmss") + ".png";
save.Filter = "(*.png)|*.png|" + "(*.*)|*.*";
save.RestoreDirectory = true;
if (save.ShowDialog() == DialogResult.OK)
{
Bitmap img = new Bitmap(zPalCon.Width, zPalCon.Height);
zPalCon.DrawToBitmap(img, new Rectangle(0, 0, img.Width, img.Height));
img.Save(save.FileName);
}
save.Dispose();
}
以下是效果图.
移动前:
移动后:
动态展示效果: