【问题标题】:Creating a moveable control out of scratch从头开始创建可移动控件
【发布时间】:2012-03-22 01:46:00
【问题描述】:

我必须制作一个用户控件,您可以在其中移动它,但我必须从头开始(即获取控件的位置并计算鼠标移动时的差异并相应地移动控件) 这就是我现在所拥有的。

公共部分类 MainMenu : UserControl { 公共点 OldMouseLoc; 公共点 OldWindowLoc; 公共主菜单() { 初始化组件(); }

private void customButton1_MouseDown(object sender, MouseEventArgs e)
{
    OldMouseLoc = MousePosition;
    OldWindowLoc = new Point(this.Location.X + this.Parent.Location.X,this.Location.Y + this.Parent.Location.Y);
    Mover.Start();
}

private void Mover_Tick(object sender, EventArgs e)
{
    Point NewMouseLoc = MousePosition;
    if (NewMouseLoc.X > OldMouseLoc.X || true) { // ( || true is for debugging)
        this.Location = new Point(NewMouseLoc.X - OldWindowLoc.X, this.Location.Y);
        MessageBox.Show(NewMouseLoc.X.ToString() + "   " + OldWindowLoc.X.ToString()); // for debugging
    }
}

}

现在我遇到问题的原因是因为 MousePosition 是相对于屏幕顶部的,而我的控件位置是相对于其父窗口的左上角的。计算所有坐标的数学让我非常头疼,请只修复这些坐标的 X 位置,这样我就可以用它来计算 Y(这样我就可以自己学习了)。

【问题讨论】:

    标签: c# winforms window location position


    【解决方案1】:

    PointToClient 应该为您计算。您需要在控件的父级上调用此方法。

    更新:

    还要考虑稍微不同的方法。你真的不需要任何计时器或屏幕坐标:

        private Point _mdLocation;
    
        private void customButton1_MouseDown(object sender, MouseEventArgs e)
        {
            _mdLocation = e.Location;
        }
    
        private void customButton1_MouseMove(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left)
            {
                var x = this.Left + e.X - _mdLocation.X;
                var y = this.Top + e.Y - _mdLocation.Y;
                this.Location = new Point(x, y);
            }
        }
    

    【讨论】:

    • 啊,谢谢,我花了一段时间才意识到这是一种方法,而不是属性 XD
    • 我还添加了我通常用于可移动控件的代码。
    • 啊谢谢,我没想到用 mousemove 代替计时器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2020-04-21
    • 2021-04-12
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多