You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForms磁吸式可拖拽控件:多控件移位逻辑优化问询

磁吸式可拖拽控件通用算法优化需求(C# WinForms)

需求描述

  • 实现磁吸式可拖拽控件行为,以MidiNote控件为基础(后续需适配其他控件)
  • 核心交互逻辑:
    • 拖拽控件插入另外两个控件之间时,其右侧所有控件自动向右滑动腾出空间
    • 拖拽控件至最左端时,原位置的间隙自动收拢
  • 参考效果:类似Apple Final Cut Pro的磁吸时间线

当前问题

仅能实现3个控件间的拖拽移位,4个及以上控件时逻辑失效,推测需要引入递归逻辑优化。

当前实现代码(MouseMove事件)

private void PianoRoll_MouseMove(object? sender, MouseEventArgs e)
{
    const int Y_POS = 200; //arbitrary
    if (_bMouseDownOnNote)
    {
        foreach (MidiNote n in this.Controls.OfType<MidiNote>())
        {
            if (n != _noteToMove)
            {
                if (n.Bounds.Contains(new Point(e.X, Y_POS)))
                {
                    int eX = e.X; int nRight = n.Right; int nWidth = n.Width;
                    if (eX > (nRight - (nWidth / 2)))
                    {
                        Point p = new Point(nRight, Y_POS);
                        _noteToMove.Location = p;
                        //k, we've moved the note, now loop all the notes to the right of this and scoot them accordingly
                        foreach (MidiNote n2 in this.Controls.OfType<MidiNote>())
                        {
                            if (n2 != _noteToMove && n2 != n)
                            {
                                if (n2.Bounds.Contains(new Point(x: nRight, y: Y_POS)))
                                {
                                    int n2Left = n2.Left;
                                    Point p2 = new Point(n2Left + nWidth, Y_POS);
                                    n2.Location = p2;
                                    nRight = n2Left + nWidth;
                                }
                            }
                        }
                    }
                    else if (eX < (nRight - (nWidth / 2)))
                    {
                        int nLeft = n.Left;
                        Point p = new Point(nLeft - nWidth, Y_POS);
                        _noteToMove.Location = p;
                        //haven't handled for multiple notes here yet :/
                    }
                }
            }
        }
    }
}

请求

寻求通用算法优化方案,若需更多代码或上下文可告知。

内容的提问来源于stack exchange,提问作者Finch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:42:18