c# keyboard input (multiply and division) in WPF DataGrid

A A 61 Reputation points
2021-03-31T15:40:29.59+00:00

Hey,

I am doing a simple calculator as an exercise and I am quite new in c#.

How to input the multiply key and division but those which are not from NumPad?
I consider this variant but I am bot sure how to use it properly:

bool shift  = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift); case Key.D5: return (shift ? '%' : '5');

if its letter I would like it to be "Error"

Here is the code
XALM:

<Window x:Class="Calculator.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Calculator"
        mc:Ignorable="d"
        Title="Calculator" Height="361.313" Width="208.941" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" PreviewKeyDown="Window_KeyDownPreview">
    <Grid HorizontalAlignment="Left" Width="199">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="165*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="203*"/>
            <ColumnDefinition Width="6*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="One" Content="1" HorizontalAlignment="Left" Margin="13,227.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Two" Content="2" HorizontalAlignment="Left" Margin="58,227.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Three" Content="3" HorizontalAlignment="Left" Margin="103,227.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Four" Content="4" HorizontalAlignment="Left" Margin="13,182.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Five" Content="5" HorizontalAlignment="Left" Margin="58,182.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Six" Content="6" HorizontalAlignment="Left" Margin="103,182.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Seven" Content="7" HorizontalAlignment="Left" Margin="13,137.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Eight" Content="8" HorizontalAlignment="Left" Margin="58,137.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Nine" Content="9" HorizontalAlignment="Left" Margin="103,137.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Zero" Content="0" HorizontalAlignment="Left" Margin="13,273.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Plus" Content="+" HorizontalAlignment="Left" Margin="148,227.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Operand" Grid.Row="1" />
        <Button x:Name="Minus" Content="-" HorizontalAlignment="Left" Margin="148,182.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Operand" Grid.Row="1"/>
        <Button x:Name="Multiply" Content="×" HorizontalAlignment="Left" Margin="148,137.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18"  Click="Button_Operand" Grid.Row="1"/>
        <Button x:Name="Equals" Content="=" HorizontalAlignment="Left" Margin="103,273,0,0" VerticalAlignment="Top" Width="85" Height="40" FontSize="18" Click="Button_Equals" Grid.Row="1"/>
        <Button x:Name="Dot" Content="," HorizontalAlignment="Left" Margin="58,273.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Button_Click" Grid.Row="1"/>
        <Button x:Name="Clear" Content="C" HorizontalAlignment="Left" Margin="103,92.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18" Click="Clear_Click" Grid.Row="1"/>
        <Button x:Name="Divide" Content="÷" HorizontalAlignment="Left" Margin="148,92.717,0,0" VerticalAlignment="Top" Width="40" Height="40" FontSize="18"  Click="Button_Operand" Grid.Row="1"/>
        <Button x:Name="Clear_Copy" Content="CE" HorizontalAlignment="Left" Margin="13,92.717,0,0" VerticalAlignment="Top" Width="85" Height="40" FontSize="18" Click="CE_Click" Grid.Row="1"/>
        <Label x:Name="Equation" Content="" HorizontalAlignment="Left" Margin="12,16.717,0,0" VerticalAlignment="Top" Width="118" Height="31" Grid.Row="1" Language="se-SE"/>
        <Label x:Name="Display" Content="0" Height="71" Margin="10,16.717,0,0" VerticalAlignment="Top" Width="175" HorizontalAlignment="Left" FontSize="22" Language="se-SE" HorizontalContentAlignment="Right" BorderThickness="7,0,0,0" VerticalContentAlignment="Center" Grid.Row="1"/>

    </Grid>
</Window>

C#:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Calculator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //Double Value = 0; // Store Decimal and Int Values if needed
        String Operand; // Store the Operand - Will Determine the Maths
        Boolean OperandPressed;

        public MainWindow()
        {
            InitializeComponent();
            ClearAll();
        }

        public void ClearAll()
        {
            ShowNumber = 0;
            Result = 0;
            FirstNumber = 0;
            SecondNumber = 0;
            IsSecond = false;
            IsDecimal = false;
            DecimalValue = 1;
            Operand = "";
        }

        private double _showNumber;

        public double ShowNumber
        {
            get { return _showNumber; }
            set
            {
                _showNumber = value;
                Display.Content = ShowNumber.ToString();
            }
        }

        private double _firstNumber;

        public double FirstNumber
        {
            get { return _firstNumber; }
            set { _firstNumber = value; }
        }

        public double SecondNumber { get; set; }


        public double Result { get; set; }

        public bool IsSecond { get; set; }

        public bool IsDecimal { get; set; }

        public int DecimalValue { get; set; }
        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            ClearAll();
        }

        private void CE_Click(object sender, RoutedEventArgs e)
        {
            if (Operand != "")
            {
                if (SecondNumber > 0)
                {
                    SecondNumber = 0;
                    ShowNumber = SecondNumber;
                    IsDecimal = false;
                    DecimalValue = 1;
                }
                else
                {
                    Operand = "";
                    IsSecond = false;
                }
            }
            else
            {
                ClearAll();
            }
            Display.Content = "0";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            Button B = (Button)sender; // Cast Generic Object To Buttom

            //To Get Rid of the Initial 0 in the Display
            if ((Display.Content.ToString() == "0") || (OperandPressed))
            {
                Display.Content = " ";
            }

            // If Decimal Point already exsists within the Display then do not add another Dedcimal Point
            if (B.Content.ToString() == ",")
            {
                IsDecimal = true;
            }
            else
            {
                if (IsSecond)
                {
                    if (IsDecimal)
                    {
                        DecimalValue *= 10;
                        SecondNumber += double.Parse(B.Content.ToString()) / DecimalValue;
                    }
                    else
                    {
                        SecondNumber *= 10;
                        SecondNumber += double.Parse(B.Content.ToString());

                    }
                    ShowNumber = SecondNumber;
                }
                else
                {
                    if (IsDecimal)
                    {
                        DecimalValue *= 10;
                        FirstNumber += double.Parse(B.Content.ToString()) / DecimalValue;
                    }
                    else
                    {
                        FirstNumber *= 10;
                        FirstNumber += double.Parse(B.Content.ToString());

                    }

                    ShowNumber = FirstNumber;
                }


            }

            OperandPressed = false;
        }

        private void Button_Operand(object sender, RoutedEventArgs e)
        {
            Button B = (Button)sender; // Cast Obj to Button
            //if you already have 1 operand, do the calculation
            //Read in and save somewhere the operand
            //otherwise set the shownumber to 0, set IsSecond to True


            if (Operand == "")
            {
                Operand = B.Content.ToString(); // store operand
                IsSecond = true;
                ShowNumber = SecondNumber;
                IsDecimal = false;
                DecimalValue = 1;
            }
            else
            {
                DoCalcuation();
                Operand = B.Content.ToString();
            }

        }


        public void DoCalcuation()
        {
            switch (Operand)
            {
                case "+":
                    Result = FirstNumber + SecondNumber;
                    ResetAfterCalculation();
                    break;
                case "-":
                    Result = FirstNumber - SecondNumber;
                    ResetAfterCalculation();
                    break;
                case "×":
                    Result = FirstNumber * SecondNumber;
                    ResetAfterCalculation();
                    break;
                case "÷":
                    if (SecondNumber == 0)
                    {
                        MessageBox.Show("Kan inte dela med 0");
                    }
                    else
                    {
                        Result = FirstNumber / SecondNumber;
                        ResetAfterCalculation();
                    }
                    break;
                default:
                    break;
            }

        }

        public void ResetAfterCalculation()
        {
            FirstNumber = Result;
            ShowNumber = Result;
            SecondNumber = 0;
        }
        private void Button_Equals(object sender, RoutedEventArgs e)
        {
            DoCalcuation();
            Operand = "";
        }

        /*Functionality Added to make the calculator work with Keyboard NumberPad
         When the correct Key is detected it will fire off the corresponding button press*/
        private void Window_KeyDownPreview(object sender, KeyEventArgs e)
        {
            bool shift = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
            switch (e.Key)
            {
                case Key.D0:
                    Zero.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D1:
                    One.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D2:
                    Two.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D3:
                    Three.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D4:
                    Four.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D5:
                    Five.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D6:
                    Six.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D7:
                    Seven.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D8:
                    Eight.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.D9:
                    Nine.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.OemPlus:
                    Plus.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.OemMinus:
                    Minus.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.Multiply:
                    Multiply.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.OemQuestion:
                    Divide.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break; //bool shift  = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift); case Key.D5: return (shift ? '%' : '5');
                case Key.Enter:
                    Equals.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
                case Key.OemComma:
                    Dot.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                    break;
            }
        }
    }
}
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,706 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,573 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
786 questions
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,621 Reputation points
    2021-04-01T02:25:08.233+00:00

    I use the key combination Shift+D8 to realize multiply and OemQuestion to implement division. Switch the input method to English when implementing Divide with OemQuestion key. The following is my modification to your Window_KeyDownPreview`.

      private void Window_KeyDownPreview(object sender, KeyEventArgs e)  
            {  
                bool shift = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);  
                if(shift==true&& e.Key==Key.D8)  
                {  
                    Multiply.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                }  
      
                switch (e.Key)  
                {  
                    case Key.D0:  
                        Zero.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D1:  
                        One.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D2:  
                        Two.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D3:  
                        Three.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D4:  
                        Four.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D5:  
                        Five.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D6:  
                        Six.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D7:  
                        Seven.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D8:  
                        Eight.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.D9:  
                        Nine.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.OemPlus:  
                        Plus.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.OemMinus:  
                        Minus.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
      
                    case Key.Multiply:  
                        Multiply.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.Divide://division  
                        Divide.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
      
                    case Key.OemQuestion:  
                        InputLanguageManager.Current.CurrentInputLanguage = new CultureInfo("en-US");  
                        Divide.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;   
                    case Key.Enter:  
                        Equals.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                    case Key.OemComma:  
                        Dot.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));  
                        break;  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful