在一个Panel上我放了一个Picture控件,在Picture上用鼠标左键按下并拖动的时候,我用代码控制Picture的 Location让Picture能够在Panel上移动,但是我怎么才能控制鼠标不把Picture拖到Panel以外呢,就是说Picture和鼠标光标不能移动到Panel以外!

解决方案 »

  1.   

    //预感你就要这样问
    //有限制鼠标移动区域的API函数
    //ClipCursor(nil)则取消限制using System.Runtime.InteropServices;[DllImport("user32.dll")]
    public static extern bool ClipCursor(IntPtr lpRect);
    [DllImport("user32.dll")]
    public static extern bool ClipCursor(ref Rectangle lpRect);private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        Rectangle rectangle = new Rectangle(0, 0, 
            ((Control)sender).Parent.ClientSize.Width,
            ((Control)sender).Parent.ClientSize.Height);
        downPoint = e.Location;
        Point point = ((Control)sender).Parent.PointToScreen(new Point(0, 0));
        rectangle.Offset(point);
        rectangle.Width = rectangle.Width + point.X;
        rectangle.Height = rectangle.Height + point.Y;
        ClipCursor(ref rectangle);
    //.......
    }private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return; 
        ClipCursor(IntPtr.Zero);
    //.......
    }
      

  2.   

    先计算它将要移动到的点,移动前,先检测是否越界,
    例如
    if(将要移动到的左边界<Picture.left&&将要移动到的右边界>Picture.right)
      移动()
    else 
      return;
      

  3.   

    //找到一个.NET的方法
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        Cursor.Clip = new Rectangle(
            ((Control)sender).Parent.PointToScreen(new Point(0, 0)), 
            ((Control)sender).Parent.ClientSize);
    //...........
    }private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        Cursor.Clip = Rectangle.Empty;
    //..........
    }