Trackbar Mouse Click directly to Value

  • Thread starter Thread starter John
  • Start date Start date
J

John

Ok, something that I thought would be easy is giving me fits.

Using .NET 2.0 and C# I've added a Trackbar to a form. Set some values:

trackVolume.Maximum = 100;
trackVolume.Minimum = 0;
trackVolume.TickFrequence = 25;


Then I added an event for the value:

private void trackVolume_ValueChanged(object sender, EventArgs e)
{
myPlayer.volume = trackVolume.Value;
lblVolume.Text = "Volume (" + trackVolume.Value.ToString() + "%)";
}


Up till now everything's great. Next I notice that if I click to the left or
right of the current position on the slider it only moves the Value by the
LargeChange amount. Ok fine, but what I want is to go directly to the value
that the user clicked on. By default LargeChange is set to 5. So if the
trackVolume.Value is at 10 and I click on 50 then the Value becomes 15 not
50. I checked the documentation and it says the Trackbar has a Click event
and a MouseClick event, but when I go to the events in VisualStudio 2005 I
don't have either one (apparently my documentation doesn't match my version
of VisualStudio, but that's another problem).

Can anyone help me to go directly to the value that was clicked on the
trackbar?

Thanks,
John
 
Hi John

You can use the MouseDown event and capture where the mouse was clicked over
the control, then do some calculations based on mouse's X co-ordinate and
the size of your TrackBar to set it's value:

// trackVolume.Width = 200
// trackVolume.Maximum = 100
private void trackVolume_MouseDown(object sender, MouseEventArgs e)
{
trackVolume.Value = e.X / 2;
}

Regards
Dave
 
Dave,

Thanks for the help. I've generalized it a bit and it works great. Here's the code I'm using:

private void trackVolume_MouseDown(object sender, MouseEventArgs e)
{
double dblValue;

// Jump to the clicked location
dblValue = ((double) e.X / (double) trackVolume.Width) * (trackVolume.Maximum - trackVolume.Minimum);
trackVolume.Value = Convert.ToInt32(dblValue);
}


Thanks,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top