在另一个控件的可见区域内移动控件 [英] Moving a control within another control's visible area

查看:86
本文介绍了在另一个控件的可见区域内移动控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在TabPage内有一个PictureBox,当然,这个TabPageTabView的一部分,而这个TabViewForm内.我希望用户能够在标签页中移动此图片框.为此,我使用图片框的MouseDownMouseMoveMouseUp事件:

I have a PictureBox that is inside a TabPage, and of course this TabPage is part of a TabView and this TabView is inside a Form. I want users be able to move this picture box within the tab page. For this I am using the MouseDown, MouseMove and MouseUp events of the picture box:

private void pictureBoxPackageView_MouseDown(object sender, MouseEventArgs e)
{
    if (!_mapPackageIsMoving)
    {
        _mapPackageIsMoving = true;
    }
} 

private void pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e)
{
    if(_mapPackageIsMoving)
    {
        pictureBoxPackageView.Location = MousePosition; //This is not exact at all!
        return;
    }

    //Some other code for some other stuff when picturebox is not moving...
}

private void pictureBoxPackageView_MouseUp(object sender, MouseEventArgs e)
{
    if (_mapPackageIsMoving)
    {
        _mapPackageIsMoving = false; //Mouse button is up, end moving!
        return;
    }
}

但是我的问题出在MouseMove事件上.当我在按下按钮后移动鼠标时,图片框会跳出标签页的可见区域.

But my problem lies in the MouseMove event. As soon as I move mouse after button down, the picture box jumps out of tab page's visible area.

我需要知道如何仅在选项卡页的矩形内处理移动,并且如果将图片框拖出选项卡视图的可见区域,则除非用户将鼠标移到选项卡视图的内部,否则它不应再移动.可见矩形.

I need to know how to handle the move only within the rectangle of the tab page, and if picture box is being dragged out of tab view's visible area, it shouldn't move anymore unless user brings the mouse inside the tab view's visible rectangle.

任何帮助/技巧都将得到体现!

Any helps/tips will be appriciated!

推荐答案

您需要一个变量来保存PictureBox的原始位置:

You need a variable to hold the original position of the PictureBox:

HansPassant答案修改而成:

private Point start = Point.Empty;

void pictureBoxPackageView_MouseUp(object sender, MouseEventArgs e) {
  _mapPackageIsMoving = false;
}

void pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e) {
  if (_mapPackageIsMoving) {
    pictureBoxPackageView.Location = new Point(
                             pictureBoxPackageView.Left + (e.X - start.X), 
                             pictureBoxPackageView.Top + (e.Y - start.Y));
  }
}

void pictureBoxPackageView_MouseDown(object sender, MouseEventArgs e) {
  start = e.Location;
  _mapPackageIsMoving = true;
}

这篇关于在另一个控件的可见区域内移动控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆