简体   繁体   中英

Weird location while moving WinForms picbox

I couldnt figure the problem out so after debugging i finally decide to write the below.

Why is the location jumping around?! 147 86 to 294 212 then back every callback?

pic.MouseMove += my_MouseMove;

my_MouseMove(object sender, MouseEventArgs e)

Console.WriteLine("{0} {1} {2} {3}", e.X, e.Y, e.Location.X, e.Location.Y);

147 86 147 86
294 212 294 212
147 86 147 86
294 212 294 212
147 86 147 86
294 212 294 212

    //This code expects e.X,Y to return the X,Y Relative to the parent control. 
    //It seems to be relative to mousedown which breaks this.
    Point heroClick = new Point();
    private void hero_MouseDown(object sender, MouseEventArgs e)
    {
        heroClick.X = e.X;
        heroClick.Y = e.Y;
    }
    private void hero_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button != System.Windows.Forms.MouseButtons.Left)
            return;
        var xDif = e.X - heroClick.X;
        var yDif = e.Y - heroClick.Y;
        heroClick.X += xDif;
        heroClick.Y += yDif;
        lvl.playerX += xDif;
        lvl.playerY += yDif;
        PictureBox pic = ((PictureBox)sender);
        pic.Left += xDif;
        pic.Top+= yDif;
        //Console.WriteLine("{0} {1} {2} {3}", e.X, e.Y, e.Location.X, e.Location.Y, sender);
        textBox2.Text = string.Format("{0} {1} {2} {3}", e.X, e.Y, e.Location.X, e.Location.Y, sender);
        textBox2.Update();
    }

The code as posted is quite insufficient to guess what might be going on. I'll take a hint from the thread subject "while moving picBox". If you use the MouseMove event to move a control then you change the position of the control relative to the mouse. The next reported position will be different, even if you didn't move the mouse. Since the mouse position is reported relative to the upper left corner of the client area of the control.

The effect is usually very interesting, the control does the pogo, jumping back and forth rapidly. You need to compensate for this, usually by not updating the stored previous mouse position. I can't give better advice than this without seeing any relevant code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM