按Enter键时出现奇怪的行为。 [英] Strange Behavior When I Press Enter Button.

查看:82
本文介绍了按Enter键时出现奇怪的行为。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里写的计算器是使用WPF的代码。这是代码。

XAML代码。

I wrote calculator here is code using WPF.Here is code.
XAML code.

<Window x:Class="Advancedcalculator.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:sys="clr-namespace:System;assembly=mscorlib"

        Title="Advancedcalculator" Height="500" Width="400" ResizeMode="NoResize" KeyDown="iskeypressed">
    <Window.Resources>
        <sys:String x:Key="A">A String</sys:String>
    </Window.Resources>
    <Grid>
    <TextBlock x:Name="Display" Height="123" VerticalAlignment="Top" FontSize="35"/>

        <UniformGrid Width="400" Height="350" Rows="6" Columns="4" VerticalAlignment="Bottom">
        <Button  Content="7" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="8" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="9" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="/" FontSize="50" Tag="/"  Click="Someoperator" Background="White" BorderBrush="Red"/>
            <Button  Content="4" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="5" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="6" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="X" FontSize="50" Tag="*" Click="Someoperator" Background="White" BorderBrush="Red"/>
            <Button  Content="1" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="2" FontSize="50"   Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="3" FontSize="50"   Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="-" FontSize="50" Tag="-" Click="Someoperator" Background="White" BorderBrush="Red"/>
            <Button  Content="0" FontSize="50"  Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="+-" FontSize="50" Click="plusminus" Background="White" BorderBrush="Red"/>
            <Button  Content="." FontSize="50" Tag="," Click="Button_Click_digit" Background="White" BorderBrush="Red"/>
            <Button  Content="+" FontSize="50" Tag="+" Click="Someoperator" Background="White" BorderBrush="Red"/>
            <Button  Content="CLEAR" FontSize="30" Click="Clear" Background="White" BorderBrush="Red"/>
            <Button  Content="REG" FontSize="30" Click="Reg" Background="White" BorderBrush="Red"/>
            <Button  Content="=" FontSize="50" Click="Equal" Background="White" BorderBrush="Red"/>
            <Button  Content="(" FontSize="50" Tag="(" Click="openbracket" Background="White" BorderBrush="Red" />
            <Button  Content=")" FontSize="50" Tag=")" Click="closebracket" Background="White" BorderBrush="Red"/>
        </UniformGrid>
    </Grid>
</Window>



C#代码


C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Diagnostics;


namespace Advancedcalculator
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    /// 
      [DebuggerStepThrough]
    public class container //представляет собой контейнер типизированных списков для чисел и операторов
    {
        public container()
        {
            
            tempoperand.Add("");
            operands.Add(0);
            operators.Add(' ');
 
        }
        public char[] basicoperators = new char[] { '+', '-', '/', '*'};//представляет массив который содержит базовые операторы
        public List<double> operands = new List<double>();//типизированный список чисел которые мы вводим.
        public List<string> tempoperand = new List<string>();//временный список чисел который мы потом конвертируем в operands
        public List<char> operators = new List<char>();//список математических операторов
        public List<int> brecketindicators = new List<int>();
    }
    public partial class MainWindow : Window
    {
        int i = 0;
        List<container> variables = new List<container>();//список типа conteiner.
         
    
        private void dodigit<T>(object sender, T e)//метод который добаляет нажатый символ на экран,а потом записывает в tempoperand.
        {
            Display.Text += e;
            variables[variables.Count - 1].tempoperand[i] += e.ToString(); 
        }
          
        private void dooperator<T>(object sender, T e)//метод который добаляет нажатый оператор на экран.
        {
            if (variables[variables.Count - 1].basicoperators.Contains(Display.Text[Display.Text.Length - 1]) == false)
            {
                Display.Text += e;
                variables[variables.Count - 1].operands.Add(0);//Создаём новый пустой элемент списка
                variables[variables.Count - 1].operators.Add(' ');//Создаём новый пустой элемент списка
                variables[variables.Count - 1].tempoperand.Add("");//Создаём новый пустой элемент списка
                variables[variables.Count - 1].operands[i] = Convert.ToDouble(variables[variables.Count - 1].tempoperand[i]);
                variables[variables.Count - 1].operators[i] = Convert.ToChar(e);
                i = i + 1;
            }
        }
        private void doequal<T>(object sender, T e)
        {
            variables[variables.Count - 1].operands[i] = Convert.ToDouble(variables[variables.Count - 1].tempoperand[i]);
            variables[variables.Count - 1].operands[0] = calculator(variables[variables.Count - 1].operands, variables[variables.Count - 1].operators);
            if (variables.Count==1)
                Display.Text = Convert.ToString(variables[variables.Count - 1].operands[0]);
            variables[variables.Count - 1].operators.Clear();
           
            variables[variables.Count - 1].tempoperand.Clear();
            variables[variables.Count - 1].tempoperand.Add("");
            variables[variables.Count - 1].tempoperand[0] = Convert.ToString(variables[variables.Count - 1].operands[0]);
            

        }
        private void doclear<T>(object sender,T e)
        {
            Display.Text="";

            variables.Clear();
            variables.Add(new container());
           
            i = 0;
        }
        private void doreg<T>(object sender,T e)
        {
            if (variables[variables.Count - 1].basicoperators.Contains(Display.Text[Display.Text.Length - 1]) == false && Display.Text.Length>0)
            {
                if (variables[variables.Count - 1].tempoperand[i].Contains("-") == false)
                {
                    variables[variables.Count - 1].tempoperand[i] = variables[variables.Count - 1].tempoperand[i].Remove(variables[variables.Count - 1].tempoperand[i].Length - 1);
                    Display.Text = Display.Text.Remove(Display.Text.Length - 1);
                }
                
            }
        }
        private void doopenbracket<T>(object sender, T e)
        {

            variables[0].brecketindicators.Add(i);
            i = 0;
            Display.Text += "(";
            variables.Add(new container());
           
        }
        private void doclosebracket<T>(object sender, T e)
        {
            if((Display.Text.Count(x=>x=='(')-Display.Text.Count(x=>x==')'))==1)
            {
            Display.Text += e;
            doequal(sender, e);
            i = variables[0].brecketindicators[variables.Count-2];
            variables[variables.Count - 2].operands[i] = variables[variables.Count - 1].operands[0];
            variables[variables.Count - 2].tempoperand[i] = Convert.ToString(variables[variables.Count - 1].operands[0]);
            variables.RemoveAt(variables.Count - 1);
            }
           
        }
        private void dochangesign<T>(object sender, T e)
        {
            if (variables[variables.Count - 1].basicoperators.Contains(Display.Text[Display.Text.Length - 1]) == false)
            {
                if (variables[variables.Count - 1].tempoperand[i].Contains("-"))
                {
                    variables[variables.Count - 1].tempoperand[i] = variables[variables.Count - 1].tempoperand[i].Replace("-","");
                    Display.Text = Display.Text.Remove(Display.Text.Length - variables[variables.Count - 1].tempoperand[i].Length-3);
                    Display.Text += variables[variables.Count - 1].tempoperand[i];
                }
                else
                {
                    Display.Text = Display.Text.Remove(Display.Text.Length - variables[variables.Count - 1].tempoperand[i].Length);
                    variables[variables.Count - 1].tempoperand[i] = variables[variables.Count - 1].tempoperand[i].Insert(0, "-");
                    Display.Text += "(" + variables[variables.Count - 1].tempoperand[i] + ")";
                }
            }

        }
        [DebuggerStepThrough]
        public MainWindow()
        {
            InitializeComponent();
            variables.Add(new container());
          
        }
        [DebuggerStepThrough]
        private void Button_Click_digit(object sender, RoutedEventArgs e)//обработчик нажатия цифры или запятой
        {
            dodigit(sender, (e.OriginalSource as Button).Content);
        }

        [DebuggerStepThrough]
        private void Someoperator(object sender, RoutedEventArgs e)//обработчик нажатия кнопки оператора +-*/
        {
            dooperator(sender,(e.OriginalSource as Button).Tag);
        }

        private void Equal(object sender, RoutedEventArgs e)
        {
            doequal(sender,e);
        }

        private void Clear(object sender, RoutedEventArgs e)
        {
            doclear(sender, e);
        }   

        private double calculator(List<double> a,List<char> b)
        {
            Dictionary<char, Func<double, double, double>> basicmath = new Dictionary<char, Func<double, double, double>>();
            basicmath.Add('+', (i, j) => i + j);
            basicmath.Add('-', (i, j) => i - j);
            basicmath.Add('*', (i, j) => i * j);
            basicmath.Add('/', (i, j) => i / j);

            for (int k=0;k<i;k++)
            {
               if (b[k]=='/' || b[k]=='*')
               {
                   a[k] = basicmath[b[k]].Invoke(a[k],a[k+1]);
                   b.RemoveAt(k);
                   for (int j = k + 1; j < i ; j++ )
                   {
                       a[j] = a[j + 1];
                   }
                   a.RemoveAt(i);
                   i = i-1;
                   
                   k = -1;
               }
            }
            
            for (int k = 0; k < i; k++)
            {
                a[k] = basicmath[b[k]].Invoke(a[k], a[k + 1]);
                a.RemoveAt(k+1);
                b.RemoveAt(k);
                i = i - 1;
                k = -1;
                
            }
            return a[0];
        }
        private void Reg(object sender, RoutedEventArgs e)
        {
            doreg(sender,e);
        }

        private void openbracket(object sender, RoutedEventArgs e)
        {
            doopenbracket(sender, (e.OriginalSource as Button).Tag);
        }

        private void closebracket(object sender, RoutedEventArgs e)
        {
            doclosebracket(sender, (e.OriginalSource as Button).Tag);

        }
        private void plusminus(object sender, RoutedEventArgs e)
        {
            dochangesign(sender, e);
        }
        private void iskeypressed(object sender, KeyEventArgs e)
        {
           
            if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.OemPlus))
            {
                dooperator(sender, "+");
                return;
            }
            if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.D9))
            {
                doopenbracket(sender, "(");
                return;
            }
            if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.D0))
            {
                doclosebracket(sender, ")");
                return;
            }
            if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.D8))
            {
                dooperator(sender, "*");
                return;
            }
            var ch = (char)KeyInterop.VirtualKeyFromKey(e.Key);//преобразует клавишу System.Windows.Input.Key в windows 32 key.
            if (Char.IsDigit(ch))
            {
                dodigit(sender, ch);
            }
            switch (e.Key)
            {
                case Key.OemPlus: doequal(sender, e); break;
                case Key.OemMinus: dooperator(sender,"-"); break;
                case Key.Divide: dooperator(sender, "/"); break;
                case Key.Return: doequal(sender, e); break;
                case Key.Back: doreg(sender, e); break;
                case Key.OemComma :case Key.OemPeriod: dodigit(sender, ","); break;
                case Key.Escape: doclear(sender, e); break;
                case Key.OemQuestion: dooperator(sender, "/"); break;

            }
            
        }
    }
}





When i press enter i should get calculation resuts.And it works.But when i write task like this (-5,3)+(-2,3).When i press enter instead of writing results.It changes sign of 2,3 operand. private void dochangesign<t>(object sender, T e) method changes sign of operands.But it even mustn’t be implemented.With \"=\" key,everything is fine.According to



When i press enter i should get calculation resuts.And it works.But when i write task like this (-5,3)+(-2,3).When i press enter instead of writing results.It changes sign of 2,3 operand. private void dochangesign<t>(object sender, T e) method changes sign of operands.But it even mustn't be implemented.With "=" key,everything is fine.According to

case Key.Return: doequal(sender, e); break;

method doequal should works instead of it,dochangesign method works.Help me figure out why it happens.

method doequal should works instead of it,dochangesign method works.Help me figure out why it happens.

推荐答案

After you click the +/- button, the button still has focus, so pressing enter ’clicks’ the button - so changes the sign.
After you click the +/- button, the button still has focus, so pressing enter 'clicks' the button - so changes the sign.


这篇关于按Enter键时出现奇怪的行为。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆