Keyboard input of numeric values and commas as decimal separator

One of the questions I frequently get is how to get the same behavior as Excel when entering numeric values. With the same behavior I mean that Excel detects the current users locale setting for decimal separator and makes the decimal point on the numeric keyboard input the correct character. This is only done for the numeric keypad, the point and comma on regular part of the keyboard remain unchanged. Doing so is very easy but finding the right place is not completely obvious as in most events the KeyEventArgs or Message parameters cannot be changed or changing them has no effect.   The proper place to do this is the PreProcessMessage() function of a control. The code below does just that, just subclass the a TextBox control and override the PreProcessMessage() function and you are done.



PublicOverridesFunction PreProcessMessage(ByRef msg As System.Windows.Forms.Message) AsBoolean
   If msg.Msg = &H102 Then
      If msg.WParam.Equals(New IntPtr(&H2E)) _
         AndAlso msg.LParam.Equals(New IntPtr(&H530001)) Then
         ‘ Point in the numeric keypad pressed
         If Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = “,”Then
            ‘ And the decimal separator is a ‘,’ for the current settings
            ‘ Change the message to enter a comma instead of a poin
            msg.WParam = New IntPtr(&H2C)
            msg.LParam = New IntPtr(&H330001)

  ‘ Do the default actions


Now if you are using a DataGridView things are a little more complicated :-(. The code is a little long for this blog post but I did put it up on my web site. Take a look at this FAQ entry if you are interested.


Maurice de Beijer

11 thoughts on “Keyboard input of numeric values and commas as decimal separator

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>