PictureBox控件在winfrom中进行拖动,用其他大佬的方法做出来的效果如下:
在鼠标停在某一位置的时候就开始晃动,幅度很大,因此我这边做个一个改进版,胆码如下
一、初始化代码:
InitializeComponent();
this.pictureBox1.MouseUp += new MouseEventHandler(this.pictureBox1_MouseUp);
this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new MouseEventHandler(this.pictureBox1_MouseMove);
事件添加:
1.点击闪电按钮添加事件
2.双击图中三个时间进入时间程序
二、写入时间程序:
int xPos;
int yPos;
int lastx, lasty;
bool MoveFlag;
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
MoveFlag = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (MoveFlag)
{
/**********************************************/
int x = System.Math.Abs(lastx - e.X); // 改
int y = System.Math.Abs(lasty - e.Y); // 进
double dis = Math.Sqrt(x * x + y * y); // 部
if (dis > 3) // 分
{
/**********************************************/
pictureBox1.Left += Convert.ToInt32(e.X - xPos);//设置x坐标.
pictureBox1.Top += Convert.ToInt32(e.Y - yPos);//设置y坐标.
lastx = e.X;
lasty = e.Y;
textBox1.Text = pictureBox1.Left.ToString();
textBox2.Text = pictureBox1.Top.ToString();
}
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
MoveFlag = true;//已经按下.
xPos = e.X;//当前x坐标.
yPos = e.Y;//当前y坐标.
}
程序主要改进了在鼠标拖动过程中停止时,只要鼠标移动距离不超过3pix,移动程序跳过,就不会出现上述问题