Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

c# - how to move a control on mousemove in runtime?

I have a WinForm application, I'm trying to move a pictureBox in a Form using MouseMove Event, but i can't figure out what's the right calculation should i do on MouseMove, when i first the pictureBox , its location changes in a senseless way then on moving the pictureBox Location moves correctly.

It's a Panel name OuterPanel which contains the pictureBox picBox, here the code im using :

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point p = OuterPanel.PointToClient(MousePosition);
        picBox.Location = this.PointToClient(p);
    }
}

P.S : the goal is moving image after zooming in, like windows photo viewer

enter image description here

Update : ConvertFromChildToForm method

private Point ConvertFromChildToForm(int x, int y,Control control)
{
    Point p = new Point(x, y);
    control.Location = p;
    return p;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to Manage three Events to get it done correctly :

  • MouseDown
  • MouseMove
  • MouseUp

Here is a Related SO Question..

Your Code for picBox :

private void picBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point p = ConvertFromChildToForm(e.X, e.Y, picBox);
        iOldX = p.X;
        iOldY = p.Y;
        iClickX = e.X;
        iClickY = e.Y;
        clicked = true;
    }
}

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (clicked)
    {
        Point p = new Point(); // New Coordinate
        p.X =  e.X + picBox.Left;
        p.Y =  e.Y + picBox.Top;
        picBox.Left = p.X - iClickX;
        picBox.Top = p.Y - iClickY;
    }
}

private void picBox_MouseUp(object sender, MouseEventArgs e)
{
    clicked = false;   
}

private Point ConvertFromChildToForm(int x, int y, Control control)
{
    Point p = new Point(x, y);
    control.Location = p;
    return p;
}

ConvertFromChildToForm method from Mur Haf Soz


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...