Skip to content

Microsoft Excel decimal key behavior in WPF

February 16, 2012

At Reasult we develop financial forecasting software for the Real Estate sector. We have to deal with a lof of numeric input values in our WPF applications.

Al lot of our customers are used to work with Microsoft Excel. When in Excel the decimal key on the numeric keyboard is pressed always the decimal separator specfied in the regional settings is used. This is not the way a normal Windows (WPF) application handles this key.

With the following piece of code you get the same behavior as Excel.

    public class DecimalKeyTextBox : TextBox
    {
        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Decimal)
            {
                e.Handled = true;

                string decimalSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
                TextCompositionManager.StartComposition(new TextComposition(InputManager.Current, this, decimalSeparator));
            }

            base.OnKeyDown(e);
        }
    }

Whenever the decimal key on the numeric keyboard is pressed the event is cancelled and the decimal separator specified in the regional settings is used.

About these ads

From → .NET, Numeric, WPF

One Comment
  1. I always wondered how to use the TextCompositionManager, this is a good example. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: