Re: Track Bar

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



The problem is most likely because e.X is relative to the control, but
you are setting the position relative to the form. You are also not
taking into account where abouts in the image the cursor was clicked.
Here is the code I use:

private void tracker_MouseDown(object sender, MouseEventArgs e)
{
// Very small optimisation. Check here, so we don't have to check
EVERY time the mouse is moved
if (e.Button == MouseButtons.Left)
{
ShouldDrag = true;
// Store the intitial cursor position. This allows us to offset
the tracker so that it doesn't jump to the left of the cursor.
initialCursorPosition = e.X;
}
}

private void tracker_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
ShouldDrag = false;
}

private void tracker_MouseMove(object sender, MouseEventArgs e)
{
if (ShouldDrag)
{
// Move it based on the offset, not the absolute value. Also,
offset it so the tracker doesn't jump.
tracker.Left += (e.X - initialCursorPosition);
}
}

If you don't understand the "offset" things, remove that part of the
code to see. I couldn't think how best to explain it.

Hope that helps.

.


Quantcast