【问题标题】:Override OnMouseMoveEvent after creating own cs file创建自己的cs文件后覆盖OnMouseMoveEvent
【发布时间】:2019-12-26 18:12:52
【问题描述】:

我的movable_picturebox.cs 文件包含:

public class movable_picturebox : PictureBox
{

    public movable_picturebox(IContainer container)
    {
        container.Add(this);
    }

    Point point;

    protected override void OnMouseDown(MouseEventArgs e)
    {
        point = e.Location;
        base.OnMouseDown(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {

        if(e.Button == MouseButtons.Left)
        {
            this.Left += e.X - point.X;
            this.Top += e.Y - point.Y;
        }
    }

}

现在,当我在 winforms 中添加我的 moveable_picturebox 元素时,我可以通过按住鼠标将它移动到任何我想要的地方。

我需要做什么才能停止此事件?例如: 我开始程序, 我将图片框移动到特定位置, 我需要停止这个事件,不能移动这个图片框。我需要再次覆盖此事件,但是,我该怎么做?以及代码应该包含什么?

【问题讨论】:

    标签: c# winforms overriding picturebox


    【解决方案1】:

    无需再次覆盖该方法,只需在现有方法中添加另一个条件检查即可。有一个布尔值来设置你是否canMovePictureBox,并将函数更改为

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left && canMovePictureBox)
        {
            this.Left += e.X - point.X;
            this.Top += e.Y - point.Y;
        }
    }
    

    【讨论】:

    • 我会把它变成一个属性
    • 对于这些类型的东西,我通常喜欢先检查canMovePictureBox。如果事实证明您甚至无法移动鼠标按钮,则检查鼠标按钮是没有意义的(并不是说它在这里为您节省了很多精力,但肯定会在进行更复杂的检查时派上用场)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    相关资源
    最近更新 更多