с# wpf calculator button C

A A 61 Reputation points
2021-04-20T09:54:13.3+00:00

Hey,

I have been doing a calculator. Everything is operated. When I push buttons on the keyboard - it is working. But for button C which clear all I do not have a button from the keyboard. So when I want to clear all, I click on the screen this button C. And then when I type from the keyboard it will give me 0 in every case. So the problem is that the calculator is not operated with a keyboard when I click on the C. But if I continue to click on the screen without a keyboard then everything is operated.

It 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 = string.Empty;
        }

        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();
            }



            //To Do the calculaton:
            //Use your Case statement in Button_Equals,  but use FirstNumber and SecondNumber instead of Value 

            // Continously operate on the current results without having to press equals.


        }


        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);
            if (shift == true && e.Key == Key.OemQuestion)
            {
                Multiply.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            }
            else if (shift == true && e.Key == Key.Oem7)
            {
                Divide.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:
                    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;
            }
        }
    }
}

Thank you.

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,676 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,277 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.
766 questions
{count} votes