Movatterモバイル変換


[0]ホーム

URL:


Wayback Machine
32 captures
07 Dec 2008 - 01 Jun 2025
NovJANJul
Previous capture02Next capture
201020122013
success
fail
COLLECTED BY
Organization:Alexa Crawls
Starting in 1996,Alexa Internet has been donating their crawl data to the Internet Archive. Flowing in every day, these data are added to theWayback Machine after an embargo period.
Collection:Alexa Crawls
Starting in 1996,Alexa Internet has been donating their crawl data to the Internet Archive. Flowing in every day, these data are added to theWayback Machine after an embargo period.
TIMESTAMPS
loading
The Wayback Machine - https://web.archive.org/web/20120102012005/http://www.codeproject.com:80/KB/edit/NumericUpDownEx.aspx
Click here to Skip to main content
8,377,346 members and growing!
EmailPassword Lost password?
Home
Search within:




Licence CPOL
First Posted 12 Nov 2008
Views 52,918
Downloads 449
Bookmarked 69 times

Extended NumericUpDown Control

ByClaudio Nicora | 15 Mar 2010
An extended NumericUpDown control with better focus and mouse wheel management.
 
See Also
Print Article
add
Add to your CodeProject bookmarks
Discuss
Discuss this article
34
  4.79 (18 votes)

1

2
1 vote, 5.6%
3
4 votes, 22.2%
4
13 votes, 72.2%
5
4.79/5 - 18 votes
1 removed
μ 4.68, σa 1.04 [?]
Sponsored Links

Introduction

If you have ever written a data-entry application, there's a big chance you used theNumericUpDown 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 thatNumericUpDown 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 theTextBox properties, likeSelectedText,SelectionStart,SelectionLength (anAutoSelect 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, likeInterceptArrowsKeys 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 missingTextBox properties when I was asked to select all the text in the control when it got the focus.

Yes,NumericUpDown exposes aSelect(int Start,int Length) method you can call to select all text. At first try, I attached to theGotFocus event to callSelect(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 sayx=100and proceed. This works well with the keyboard focus keys (like TAB), but it's completely useless with the mouse: a mouse click raises theGotFocus 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 aSelectAll on theMouseUp 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 aTextBox, I can test it withSelectionLength>0, so I need to access the underlyingTextBox control.

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

Friend upDownEditAs 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>PublicSubNew()MyBase.New()' extract a reference to the underlying TextBox field    _textbox = GetPrivateField(Me)If _textboxIsNothingThenThrowNew ArgumentNullException(Me.GetType.FullName _                &": Can't find internal TextBox field.")EndIf' ...EndSub'''<summary>''' Extracts a reference to the private underlying textbox field'''</summary>PrivateSharedFunction GetPrivateField _                    (ByVal ctrlAs NumericUpDownEx)As TextBox' find internal TextBoxDim textFieldInfoAs 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 textFieldInfoIsNothingThenReturnNothingElseReturnTryCast(textFieldInfo.GetValue(ctrl), TextBox)EndIfEndFunction

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

<Browsable(False)> _<DesignerSerializationVisibility( _     DesignerSerializationVisibility.Hidden)> _PublicProperty SelectionStart()AsIntegerGetReturn _textbox.SelectionStartEndGetSet(ByVal valueAsInteger)        _textbox.SelectionStart = valueEndSetEndProperty

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.ProtectedOverridesSub OnMouseUp(ByVal meventAs MouseEventArgs)If _autoSelectAndAlso _textbox.SelectionLength =0Then        _textbox.SelectAll()EndIfMyBase.OnMouseUp(mevent)EndSub

Mouse Events Not Raised Properly

The originalMouseEnter andMouseLeave events are raised in couples: aMouseEnter immediately followed by aMouseLeave. Maybe that's why, to discourage their use, they are marked with a<Browsable(False)> attribute. Since I need theMouseEnter event to update myStatusBar caption, I investigated a little on this "bug".

As said above,NumericUpDown is a composite control (red rectangle in the following picture) containing aTextBox (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 theMouseEnter event while between the red and the green, thenMouseLeave when inside the green rectangle. The same happens when you leave.

The better way to raise these events, now that we can access the underlyingTextBox, is to re-raise theMouseEnter andMouseLeave events as raised from theTextBox itself; this is whatNumericUpDownEx 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 areNumericUpDown ones:

After your user puts the focus inside one of them, the mouse wheel is captured by theNumericUpDown. 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 theWM_MOUSEWHEEL message for the control, but this will kill even "legal" wheelings.

TheNumericUpDown has a property which allowsWM_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 theMouseEnter-MouseLeave events, then killingWM_MOUSEWHEEL messages accordingly.

How To Use the Control

Simply includeNumericUpDownEx.vb in your project and use the control like you'll do with the standardNumericUpDown. If you have a C# project, you could reference theCoolSoft.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.

Updates

v1.3 (15/Mar/2010)

  • Added newWrapValue property: when set, if Maximum is reached during an increment, Value will restart from Minimum (and vice versa)
    (feature suggested by YosiHakelhere)
  • Cleaned up the C# version

v1.2 (10/Feb/2010)

  • Added two new eventsBeforeValueDecrement andBeforeValueIncrement, as suggested byandrea@gmi. This will allow to give different increment/decrement depending on current control value
  • Added a C# version of the control to the ZIP

License

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

About the Author

Claudio Nicora

Systems / Hardware Administrator
CoolSoft
Italy Italy

Member
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 ofDeCodEx (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 Developer and SysAdmin life easier.
 
You can find them here:http://coolsoft.altervista.org.

loading...
Sign Up to vote  PoorExcellent
Add a reason or comment to your vote:x
Votes of 3 or less require a comment

Comments and Discussions

 
 RefreshFirstPrevNext
QuestionGreat arrowsmembersilvio pontes23:16 9 Nov '11  
AnswerRe: Great arrowsmemberClaudio Nicora23:25 4 Dec '11  
GeneralBehavior when user clears the textmemberMWBate9:26 14 Feb '11  
GeneralHiding the Up/Down arrowsmemberOrf12:29 17 Dec '10  
QuestionNumericUpDown click-to-send feature C# missing ??memberSam Tal20:57 30 Sep '10  
AnswerRe: NumericUpDown click-to-send feature C# missing ??memberClaudio Nicora21:58 30 Sep '10  
GeneralLocation change problemmemberpampasit18:15 25 May '10  
GeneralRe: Location change problemmemberClaudio Nicora21:58 25 May '10  
GeneralRe: Location change problemmemberpampasit23:05 25 May '10  
GeneralRe: Location change problemmemberClaudio Nicora6:32 26 May '10  
Last Visit: 19:00 31 Dec '99     Last Update: 15:20 1 Jan '121234Next »

General General   News News   Suggestion Suggestion   Question Question   Bug Bug   Answer Answer   Joke Joke   Rant Rant   Admin Admin   

Permalink |Advertise |Privacy |Mobile
Web03 |2.5.111208.1 |Last Updated 15 Mar 2010
Article Copyright 2008 by Claudio Nicora
Everything elseCopyright ©CodeProject, 1999-2012
Terms of Use
Layout:fixed|fluid

The Daily Insider

[8]ページ先頭

©2009-2025 Movatter.jp