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 setting for decimal separator and makes the 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.
Public
Overrides
Function
PreProcessMessage( _
ByRef msg
As
System.Windows.Forms.Message)
As
Boolean
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)
End
If
End
If
End
If
' Do the default
actions
Return
MyBase.PreProcessMessage(msg)
End
Function
Note: If you are using a DataGridView things are a little more
complicated. See the DataGridView
entry for all the code required there.