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

时间:2011-10-17 17:56:38

标签: c# winforms

我有一个winforms应用程序。在里面,我有一个面板(panel1),在这个面板内,另一个面板(面板2)里面有按钮。 当我在某个按钮中mousedown时,我想在panel1中水平移动panel2。 我在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;
        }
    }

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

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

而不是

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

但是panel2消失了。我想知道如何仅在水平方向上移动panel2内的panel2。

非常感谢。

3 个答案:

答案 0 :(得分:4)

    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 */);
        }
    }

答案 1 :(得分:0)

这不是最干净的实现,但如果我理解你正在尝试做什么,它就有效:

        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;
    }

答案 2 :(得分:0)

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

此外,如果您让用户拖动东西,我强烈建议您不要移动面板,除非拖动超过一个小阈值。单击屏幕时,很容易意外地将鼠标移动几个像素。

例如:

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