Click here to Skip to main content
5,787,682 members and growing! (16,203 online)
Email Password   helpLost your password?
Desktop Development » Edit Controls » General     Intermediate License: The Code Project Open License (CPOL)

Extended NumericUpDown control

By Claudio Nicora

An extended NumericUpDown control with better focus and mouse wheel management.
VB (VB 8.0, VB), C# 2.0, C#, .NET (.NET, .NET 2.0), WinForms, Design, Dev

Posted: 12 Nov 2008
Updated: 12 Nov 2008
Views: 5,483
Bookmarked: 34 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
11 votes for this Article.
Popularity: 4.83 Rating: 4.64 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 9.1%
3
2 votes, 18.2%
4
8 votes, 72.7%
5

Introduction

If you have ever written a data-entry application, there's a big chance you used the NumericUpDown control. This control is great to provide a field to enter numeric values, with advanced features like up-down buttons and accelerating auto-repeat.

The other side of the coin is that NumericUpDown is not really mouse-aware. I experienced some bugs and bad behaviors:

  • I need to select all the text when it gets focus (see below), but it misses some of the TextBox properties, like SelectedText, SelectionStart, SelectionLength (an AutoSelect property will be useful).
  • Some of the standard events are not working properly (see below): MouseEnter, MouseLeave.
  • Rotating the mouse wheel when the control is focused causes its value to change. A property to change this behavior, like InterceptArrowsKeys for up/down keys, will be useful.

That's why I decided to subclass it, fixing these points and adding missing features and properties.

Missing TextBox properties

I needed some missing TextBox properties when I was asked to select all the text in the control when it got the focus.

Yes, NumericUpDown exposes a Select(int Start, int Lenght) method you can call to select all text. At first try, I attached to the GotFocus event to call Select(0, x) but, hey, wait a moment... what should I use for x? It seems that any value is accepted, even if greater than the text length. OK, let's say x=100 and proceed. This works well with the keyboard focus keys (like TAB), but it's completely useless with the mouse: a mouse click raises the GotFocus event (where I select all the text), but as soon as you release the button, a zero-selection is done, leaving the control with no selection. OK, I thought, let's add a SelectAll on the MouseUp event too, but this way, the user cannot perform a partial selection anymore; each time the mouse button is released, all the text is selected. I need to know if a partial selection exists; in a TextBox, I can test it with SelectionLength > 0, so I need to access the underlying TextBox control.

Now comes the tricky part: NumericUpDown is a composite control, a TextBox and a button box. Looking inside it through the Reflector, we can find the internal field which holds the textbox part:

Friend upDownEdit As UpDownEdit  ' UpDownEdit inherits from TextBox

We'll obtain a reference to this field using Reflection; this is done in the control creator.

''' <summary>
''' object creator
''' </summary>
Public Sub New()
    MyBase.New()
    ' extract a reference to the underlying TextBox field
    _textbox = GetPrivateField(Me)
    If _textbox Is Nothing Then
        Throw New ArgumentNullException(Me.GetType.FullName _
                & ": Can't find internal TextBox field.")
    End If
    ' ...
End Sub


''' <summary>
''' Extracts a reference to the private underlying textbox field
''' </summary>
Private Shared Function GetPrivateField _
                    (ByVal ctrl As NumericUpDownEx) As TextBox
    ' find internal TextBox
    Dim textFieldInfo As Reflection.FieldInfo _
        = GetType(NumericUpDown).GetField("upDownEdit", _
                    Reflection.BindingFlags.FlattenHierarchy _
                    Or Reflection.BindingFlags.NonPublic _
                    Or Reflection.BindingFlags.Instance)
    ' take some caution... they could change field name
    ' in the future!
    If textFieldInfo Is Nothing Then
        Return Nothing
    Else
        Return TryCast(textFieldInfo.GetValue(ctrl), TextBox)
    End If
End Function

Now that we have the underlying TextBox, it is possible to export some missing properties:

<Browsable(False)> _
<DesignerSerializationVisibility( _
     DesignerSerializationVisibility.Hidden)> _
Public Property SelectionStart() As Integer
    Get
        Return _textbox.SelectionStart
    End Get
    Set(ByVal value As Integer)
        _textbox.SelectionStart = value
    End Set
End Property

And finally, we can have a perfectly working mouse management:

' MouseUp will kill the SelectAll made on GotFocus.
' Will restore it, but only if user have not made
' a partial text selection.
Protected Overrides Sub OnMouseUp(ByVal mevent As MouseEventArgs)
    If _autoSelect AndAlso _textbox.SelectionLength = 0 Then
        _textbox.SelectAll()
    End If
    MyBase.OnMouseUp(mevent)
End Sub

Mouse events not raised properly

The original MouseEnter and MouseLeave events are raised in couples: a MouseEnter immediately followed by a MouseLeave. Maybe that's why, to discourage their use, they are marked with a <Browsable(False)> attribute. Since I need the MouseEnter event to update my StatusBar caption, I investigated a little on this "bug".

As said above, NumericUpDown is a composite control (red rectangle in the following picture) containing a TextBox (left green rectangle) and some other controls:

The "control" area is the one between the red and the green rectangles; when you fly over it with the mouse, you'll receive the MouseEnter event while between the red and the green, then MouseLeave when inside the green rectangle. The same happens when you leave.

The better way to raise these events, now that we can access the underlying TextBox, is to re-raise the MouseEnter and MouseLeave events as raised from the TextBox itself; this is what NumericUpDownEx does.

MouseWheel management

NumericUpDown's management of the mouse wheel is, sometimes, really annoying. Suppose you have an application which displays some kind of chart, with a topmost dialog (toolbox) to let the user change some parameters of the graph. In this dialog, the only controls which can keep the focus are NumericUpDown ones:

After your user puts the focus inside one of them, the mouse wheel is captured by the NumericUpDown. When the user wheels to, say, scroll the graph, the effect is that the focused field value is changed; this behavior is really annoying.

A fix could be to kill the WM_MOUSEWHEEL message for the control, but this will kill even "legal" wheelings.

The NumericUpDown has a property which allows WM_MOUSEWHEEL messages to pass only if the mouse pointer is over the control, making sure that the user is wheeling to change the control value.

This is done by keeping track of the mouse state in the MouseEnter-MouseLeave events, then killing WM_MOUSEWHEEL messages accordingly.

How to use the control

Simply include NumericUpDownEx.vb in your project and use the control like you'll do with the standard NumericUpDown. If you have a C# project, you could reference the CoolSoft.NumericUpDownEx.dll assembly or, better, try to convert the code to C# (it should not be so difficult). I could provide a C# version upon request.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Claudio Nicora


I started programming in the early 1984, when I was 12, using each and every version of VB, from QuickBasic (1985) to VB.NET 9.0, but also Fortran, Pascal, Modula2, C++, C#, PHP.

I'm the author of DeCodEx (DEsigner CODe EXtractor), a free tool to split VisualStudio 2003 forms and controls source code into the new 2005/2008 partial classes format (*.vb and *.Designer.vb, or *.cs and *.Designer.cs).

I like writing tools to make my programmer and SysAdmin life easier.

You could find some of them on http://coolsoft.altervista.org website.
Occupation: Systems / Hardware Administrator
Company: CoolSoft
Location: Italy Italy

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
GeneralUpDownButtons and MouseLeavememberM McCracken11:24 9 Dec '08  
GeneralRe: UpDownButtons and MouseLeavememberClaudio Nicora23:48 9 Dec '08  
GeneralRe: UpDownButtons and MouseLeave [modified]memberM McCracken3:20 10 Dec '08  
GeneralRe: UpDownButtons and MouseLeavememberClaudio Nicora22:08 10 Dec '08  
GeneralFormatting the valuememberdoshe12:18 4 Dec '08  
GeneralRe: Formatting the valuememberClaudio Nicora22:51 4 Dec '08  
GeneralGreatmemberMember 46847457:38 25 Nov '08  
JokeRe: GreatmemberClaudio Nicora12:59 25 Nov '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Nov 2008
Editor: Smitha Vijayan
Copyright 2008 by Claudio Nicora
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project