当前位置: 移动技术网 > IT编程>开发语言>c# > C#控件Picturebox实现鼠标拖拽功能

C#控件Picturebox实现鼠标拖拽功能

2019年07月18日  | 移动技术网IT编程  | 我要评论

工作需要,要在一个form里面实现一个实时预览的picturebox图像,由于picturebox可能会遮挡到其后面的画面,所以要求picturebox可以由用户自行拖拽,类似于悬浮框。

原理说明

在网上兜了几圈之后,决定用三段代码实现。首先要注册鼠标的三个事件:移动、鼠标左键按下、鼠标左键抬起,当然,都是在picturebox上的动作。注册三个事件后,即可以在三个对应的事件函数里面实现拖拽。

代码实例

首先在窗体设计器生成的代码里面注册picturebox的鼠标事件。注:网上说当你添加picturebox的时候,这个相应的鼠标事件就自动给添加上了,本人在实践中一开始没有手动去注册此事件,结果实验的时候对应的鼠标事件函数就是不触发,后来翻看设计器自动生成的初始化模块private void initializecomponent() ,发现并没有自动添加鼠标事件,自己手动添加后才顺利运行,博友请先查看自己的有没有自动生成,如果自动添加上了,就不用手动写了。
注册鼠标事件代码实例(自动生成的部分已省略未写):

private void initializecomponent()
{
  // 
  // realplaywnd
  // 
  this.realplaywnd.mouseup += new mouseeventhandler(this.realplaywnd_mouseup);
  this.realplaywnd.mousedown += new mouseeventhandler(this.realplaywnd_mousedown);
  this.realplaywnd.mousemove += new mouseeventhandler(this.realplaywnd_mousemove);

}

实现代码实例:

int xpos;
int ypos;
bool moveflag;
  //在picturebox的鼠标按下事件里,记录三个变量.
  private void realplaywnd_mousedown(object sender, system.windows.forms.mouseeventargs e)
  {
    moveflag = true;//已经按下.
    xpos = e.x;//当前x坐标.
    ypos = e.y;//当前y坐标.
  }

 //在picturebox的鼠标按下事件里.
 private void realplaywnd_mouseup(object sender, mouseeventargs e)
 {
   moveflag = false; 
 }

 //在picturebox鼠标移动
 private void realplaywnd_mousemove(object sender, mouseeventargs e)
 { 
   if (moveflag)
   {
     realplaywnd.left += convert.toint16(e.x - xpos);//设置x坐标.
     realplaywnd.top += convert.toint16(e.y - ypos);//设置y坐标.
   }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网