c#用MouseMove事件水平移动面板

本文关键字:移动 水平 事件 MouseMove | 更新日期: 2023-09-27 18:11:24

我有一个winforms应用程序。里面,我有一个面板(panel1),并在这个面板内,另一个面板(panel2)与按钮里面。我想把panel2水平移动到panel1里面当我在某个按钮上鼠标下移的时候。我在panel2中的每个按钮中都做了这个。

this.button4.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btMouseDown);
        this.button4.MouseMove += new System.Windows.Forms.MouseEventHandler(this.btMouseMove);
        this.button4.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btMouseUp);

void btMouseMove(object sender, MouseEventArgs e)
    {
        if (_mouseDown)
            panel2.Location = PointToClient(this.panel2.PointToScreen(new Point(e.X - _mousePos.X, e.Y - _mousePos.Y)));            
    }
    void btMouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            _mouseDown = true;
            _mousePos = new Point(e.X, e.Y);
        }
    }
    void btMouseUp(object sender, MouseEventArgs e)
    {
        if (_mouseDown)
        {
            _mouseDown = false;
        }
    }

此代码将panel2正确地移动到panel1内部,但我只想水平移动面板,此代码将移动到鼠标位置。我试着把

Point(e.X - _mousePos.X, 3)

代替

Point(e.X - _mousePos.X, e.Y - _mousePos.Y)

但是panel2消失了。我想知道如何移动panel2在panel1只有水平。

c#用MouseMove事件水平移动面板

    void btMouseMove(object sender, MouseEventArgs e) {
        if (_mouseDown) {
            int deltaX = e.X - _mousePos.X;
            int deltaY = e.Y - _mousePos.Y;
            panel2.Location = new Point(panel2.Left + deltaX, panel2.Top /* + deltaY */);
        }
    }

这不是最干净的实现,但如果我正确理解您要做的事情,它可以工作:

        int _x = 0;
    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if(_x == 0)
        {
            _x = e.X;
        }
        int move = 0;
        Point p;
        if (e.X <= _x)
        {
            move = _x - e.X;
            p = new Point(panel2.Location.X - move, panel2.Location.Y);
        }
        else
        {
            move = e.X - _x;
            p = new Point(panel2.Location.X + move, panel2.Location.Y);
        }
        panel2.Location = p;
    }

移动时需要考虑panel2的当前位置。您不需要在客户端坐标和屏幕坐标之间转换鼠标位置,因为您只需要delta。

另外,如果你让用户拖拽东西,我强烈建议你不要移动面板,除非拖拽超过了一个小的阈值。点击屏幕时很容易不小心将鼠标移动几个像素。

例如:

if (delta > 3)  { // only drag if the user moves the mouse over 3 pixels
    panel2.Location = ...
}