I'm making a User Control to act as a TrackBar. I have a ToolboxCustomTrackbar1
which has a Min
and Max
as well as a SelectedMin
which can be changed by the user dragging around a MinPanel
in the area.
The MinPanel
is drawn based on SelectedMin
, which is changed with the following code:
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if(e.Button == MouseButtons.Left)
{
UpdateSelectedMinFromMouse(e.X);
}
}
private void UpdateSelectedMinFromMouse(float x)
{
var percentage = x * 100 / Width;
var range = Max - Min;
var rawValue = percentage * range / 100;
var value = rawValue + Min;
SelectedMin = (int)Math.Round(value);
}
MinPanel
is then drawn with the following code:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1);
minPanel.Location = new Point((int)GetPosition(ref selectedMin), 0);
minPanel.Size = new Size(PanelWidth, Height/2);
minPanel.BackColor = Color.Red;
trackbarArea = new Rectangle(Buffer, 0, Width - Buffer * 2, Height);
e.Graphics.FillRectangle(Brushes.LightBlue, trackbarArea);
}
private float GetPosition(ref int input)
{
var range = Max - Min;
var value = input - Min;
var percentage = (float)value * 100 / range;
var position = percentage * Width / 100;
Console.WriteLine(position);
return position - (float)minPanel.Width / 2;
}
This all works fine and draws the MinPanel
wherever I click and drag on the control. However, I want to allow for a buffer area on the left and right of the control so as to draw the entire MinPanel
even when it's at the left and right edges of the control.
I'm currently trying to do this with:
Rectangle trackbarArea = new Rectangle(Buffer, 0, Width - Buffer * 2, Height);
And this creates the area which I actually want to be considered the range for my TrackBar
.
However, I can't seem to figure out how to have my control treat the Left edge of trackbarArea
as the Min spot and the Right edge as the Max spot.
How can I allow my TrackBar to work with a Buffer on either side of it?
I created a
ShiftOffset
variable which I essentially use to offset both theMin
and theMax
:Then, everytime I set a value, I
ValidateValue()
using:In my
User Control
initialization, I setShiftOffset = NormalizeSize(PanelWidth * 100);
but I have yet to figure out what the appropriate value forShiftOffset
is in order to leave room to draw the last half of thePanels
.I'm trying to do some sort of
PanelWidth * (Max - Min) / Width
or some variation, but I can't quite get it.