As you know, I've been having a spot of bother on a .Net Compact Framework 2.0 application with the numeric up-down control. See - here
So, rather than deploying .Net Compact 3.5 runtimes to lots of devices which wasn't really an option, I decided to build my own spinner control that can cope with numbers greater than 32767.
Solutions for this already exist in libraries like www.opennetcf.org but I needed to not add any more overhead to my application.
So, I came up with a very simple user control to-do the job for me.
This is what I came up with. Note my elevator buttons that switch on and off depending of whether you are at the top or bottom of the range.
Quite simply its a textbox and couple of pictures placed on a user control. However the interesting part of this control is how to make it spin... When the user holds their finger or stylus on one of the buttons it increments/decrements the count until the control is released.
This is achieved of course with the mousedown and mouseup events and a background thread. If we look at the down arrow I have the following code.
private void pbdown_MouseDown(object sender, MouseEventArgs e)
{
directionup = false;
increment();
}
private void pbdown_MouseUp(object sender, MouseEventArgs e)
{
running = false;
}
The magic happens in the increment method which starts a background thread
private void increment()
{
ThreadStart threadstart = new ThreadStart(run);
incthrd = new Thread(threadstart);
incthrd.Start();
}
private void run()
{
running = true;
while (running)
{
if (!Valid) return;
if (directionup)
{
Value++;
}
else
{
Value--;
}
if (running) Thread.Sleep(100); // speed of the spin
}
}
Finally a property is used (Value) to set using a control invoke the correct contents of the textbox.
As follows -
public decimal Value
{
get
{
return ourvalue;
}
set
{
decimal oldvalue = ourvalue;
ourvalue = value;
ourvalue = Math.Max(ourvalue, Minimum);
ourvalue = Math.Min(ourvalue, Maximum);
textBox1.Invoke(new EventHandler(updatetext));
}
}
When the textbox value is changed, I fire an event so the form with the control on it gets an event that something has happened.
public void updatetext(object o, EventArgs e)
{
this.textBox1.Text = ourvalue.ToString("0");
textboxmirror = this.textBox1.Text;
this.textBox1.SelectAll();
pbup.Visible = ourvalue != Maximum & enabled & visible;
pbdown.Visible = ourvalue != Minimum & enabled & visible;
if (ValueChanged != null) ValueChanged(this, ourvalue); // Fire an event
}
So our problems with the numeric-up-down control resolved. The other bonus is that I now can regulate the speed of the spinner when we hold the mouse down. Speeding it up faster than the .Net Compact Frameworks inbuilt control is perceived by the user as a performance improvement (bonus).