terça-feira, abril 03, 2012

Calculadora C# Completa e Funcional


Bom amigos depois de algum tempo sem posta nem um conteúdo novo no blog resolvi desenvolver essa calculadora Dark Pink em C# completa e funcional.
                 
      Confesso que pensei em desistir, às coisas estavam ficando um pouco complicada na minha vida, uma decepção atrás da outra. Hoje então meu mundo desabou, mas vou continuar não vai ser alguns obstáculos e decepções que vai conseguir me parar, você deve esta pensando o que tenho com isso? Simples se você esta desanimado e pensando em desistir, aconselho a não fazer isso, vamos seguir em frente ai, “No fim tudo dá certo, se não deu certo é porque ainda não chegou o fim” – Fernando Sabino.

Então vamos ao que interessa, esta calculadora é voltada para o público feminino do blog que tenho certeza que é quase zero, se não for zero, mas vamos lá, embaixo esta o código para o Design da calculadora e o que faz efetuar os cálculos, tem alguns bugs, mas não deixa de ser interessante.


Imagem da calculadora







Código do design



<Window x:Class="Calculadora.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="389" Width="283" Background="White" WindowStyle="ThreeDBorderWindow">
    <Grid Width="264" Height="351">
        <Grid.Background>
            <ImageBrush ImageSource="/WpfApplication1;component/Images/Pink_by_DaniieeLaaa.jpggirl_.jpg" />
        </Grid.Background>
        <Button Content="7" Height="28" HorizontalAlignment="Left" Margin="12,130,0,0" Name="sete" VerticalAlignment="Top" Width="37" Click="sete_Click" />
        <TextBox Height="41" HorizontalAlignment="Right" Margin="0,49,43,0" Name="display" VerticalAlignment="Top" Width="209" FontFamily="Arial" FontSize="28" HorizontalContentAlignment="Right" Background="#3EFF0000" />
        <Button Content="8" Height="28" HorizontalAlignment="Left" Margin="55,130,0,0" Name="oito" VerticalAlignment="Top" Width="37" Click="oito_Click" />
        <Button Content="9" Height="28" HorizontalAlignment="Left" Margin="98,130,0,0" Name="nove" VerticalAlignment="Top" Width="37" Click="nove_Click" />
        <Button Content="4" Height="28" HorizontalAlignment="Left" Margin="12,164,0,0" Name="quatro" VerticalAlignment="Top" Width="37" Click="quatro_Click" />
        <Button Content="5" Height="28" HorizontalAlignment="Left" Margin="55,164,0,0" Name="cinco" VerticalAlignment="Top" Width="37" Click="cinco_Click" />
        <Button Content="6" Height="28" HorizontalAlignment="Left" Margin="98,164,0,0" Name="seis" VerticalAlignment="Top" Width="37" Click="seis_Click" />
        <Button Content="1" Height="28" HorizontalAlignment="Left" Margin="12,198,0,0" Name="um" VerticalAlignment="Top" Width="37" Click="um_Click" />
        <Button Content="2" Height="28" HorizontalAlignment="Left" Margin="55,0,0,125" Name="dois" VerticalAlignment="Bottom" Width="37" Click="dois_Click" />
        <Button Content="3" Height="28" HorizontalAlignment="Left" Margin="98,198,0,0" Name="tres" VerticalAlignment="Top" Width="37" Click="tres_Click" />
        <Button Content="0" Height="28" HorizontalAlignment="Left" Margin="12,232,0,0" Name="zero" VerticalAlignment="Top" Width="80" Click="zero_Click" />
        <Button Content="," HorizontalAlignment="Left" Margin="98,232,0,91" Name="virgula" Width="37" FontSize="18" Click="virgula_Click" />
        <Button Content="+" Height="28" HorizontalAlignment="Left" Margin="141,232,0,0" Name="soma" VerticalAlignment="Top" Width="37" Click="soma_Click" />
        <Button Content="-" Height="28" HorizontalAlignment="Left" Margin="141,198,0,0" Name="subtracao" VerticalAlignment="Top" Width="37" Click="subtracao_Click" />
        <Button Content="*" Height="28" HorizontalAlignment="Left" Margin="141,0,0,159" Name="multiplicacao" VerticalAlignment="Bottom" Width="37" Click="multiplicacao_Click" />
        <Button Content="/" Height="28" HorizontalAlignment="Left" Margin="141,130,0,0" Name="divisao" VerticalAlignment="Top" Width="37" Click="divisao_Click" />
        <Button Content="=" Height="60" HorizontalAlignment="Left" Margin="184,200,0,0" Name="igual" VerticalAlignment="Top" Width="37" Click="igual_Click" />
        <Button Content="1/x" Height="28" HorizontalAlignment="Left" Margin="184,0,0,159" Name="inverso" VerticalAlignment="Bottom" Width="37" Click="inverso_Click" />
        <Button Content="%" Height="28" HorizontalAlignment="Left" Margin="184,130,0,0" Name="percente" VerticalAlignment="Top" Width="37" />
        <Button Content="&lt;--" Height="28" HorizontalAlignment="Left" Margin="12,96,0,0" Name="voltar" VerticalAlignment="Top" Width="37" Click="voltar_Click" />
        <Button Content="CE" Height="28" HorizontalAlignment="Left" Margin="55,96,0,0" Name="button1" VerticalAlignment="Top" Width="37" Click="button1_Click" />
        <Button Content="C" Height="28" HorizontalAlignment="Left" Margin="98,96,0,0" Name="button2" VerticalAlignment="Top" Width="37" Click="button2_Click" />
        <Button Height="28" HorizontalAlignment="Right" Margin="0,96,43,0" Name="raiz" VerticalAlignment="Top" Width="37" Content="√" Click="raiz_Click" />
        <Button Height="28" HorizontalAlignment="Left" Margin="141,96,0,0" Name="maisoumenos" VerticalAlignment="Top" Width="37" Content="±" Click="maisoumenos_Click" />
        <Rectangle Height="30" HorizontalAlignment="Left" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="268" Fill="#52000000" Margin="-4,-1,0,0" />
        <Rectangle Height="36" HorizontalAlignment="Left" Margin="0,315,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="265" Fill="#7C000000" />
        <Label Content="Dionatan Alves Vieira" Height="28" HorizontalAlignment="Left" Margin="12,323,0,0" Name="label1" VerticalAlignment="Top" Width="211" Foreground="White" />
        <Label Content="Calculadora C#" Height="28" HorizontalAlignment="Left" Margin="80,0,0,0" Name="label2" VerticalAlignment="Top" Width="98" Foreground="White" />
    </Grid>
</Window>


Código Para Efetuar os Cálculos


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;

namespace Calculadora
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        double acumula = 0;
        string operacao = "";
        public MainWindow()
        {
            InitializeComponent();
        }

        private void sete_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "7";
        }

        private void zero_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "0";
        }

        private void um_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "1";
        }

        private void dois_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "2";
        }

        private void tres_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "3";
        }

        private void quatro_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "4";
        }

        private void cinco_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "5";
        }

        private void seis_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "6";
        }

        private void oito_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "8";
        }

        private void nove_Click(object sender, RoutedEventArgs e)
        {
            display.Text += "9";
        }

        private void soma_Click(object sender, RoutedEventArgs e)
        {
          
            if (operacao == "*" || operacao=="-" || operacao == "/")
            {
                operacao = "+";
            }
            else
            {
                acumula += double.Parse(display.Text);
                display.Text = "";
                operacao = "+";
            }

        }

        private void igual_Click(object sender, RoutedEventArgs e)
        {
            if (operacao == "+")
            {
                acumula += double.Parse(display.Text);
                display.Text = acumula.ToString();
            }
            else if (operacao == "-")
            {
                acumula -= double.Parse(display.Text);
                display.Text = acumula.ToString();
            }
            else if (operacao=="*"){
                acumula *= double.Parse(display.Text);
                display.Text = acumula.ToString();
            }
            else if (operacao == "/") {
                if (double.Parse(display.Text) != 0)
                {
                    acumula /= double.Parse(display.Text);
                    display.Text = acumula.ToString();
                }
                else {
                    display.Text = "Dividindo por zero";
                }
            }
        }

        private void virgula_Click(object sender, RoutedEventArgs e)
        {
            display.Text += ",";
        }

        private void subtracao_Click(object sender, RoutedEventArgs e)
        {
            if (operacao == "*" || operacao == "+" || operacao == "/")
            {
                operacao = "-";
            else {
                acumula = double.Parse(display.Text);
                display.Text = "";
                operacao = "-";
            }
        }

        private void multiplicacao_Click(object sender, RoutedEventArgs e)
        {
            if (operacao == "-" || operacao == "+" || operacao == "/")
            {
                operacao = "*";
            }
            else
            {
                acumula = double.Parse(display.Text);
                display.Text = "";
                operacao = "*";
            }
        }

        private void divisao_Click(object sender, RoutedEventArgs e)
        {
            if (operacao == "*" || operacao == "+" || operacao == "-")
            {
                operacao = "/";
            }
            else
            {
            acumula = double.Parse(display.Text);
            display.Text = "";
            operacao = "/";}
        }

        private void voltar_Click(object sender, RoutedEventArgs e)
        {
            int x = display.Text.Length-1;
            if (x >= 0)
            {
                display.Text = display.Text.Substring(0, x);
            }
        }

        private void inverso_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                double d = double.Parse(display.Text);
                if (d == 0)
                {
                    display.Text = "Dividindo por zero!!!";
                }
                else
                {
                    d = 1 / d;
                    display.Text = d.ToString();
                }
            }
            catch (Exception Ex) {
              
                for (int i = 0; i < 100000; i++)
                {
                    display.Text = "Para com isso pisicopata. ";
                    // em espera.
                }
                display.Text = "";

            }
        }

        private void raiz_Click(object sender, RoutedEventArgs e)
        {
            double x = double.Parse(display.Text);
            if (x < 0)
            {
                display.Text = "Este valor não é valido.";
            }
            else {
                x = Math.Sqrt(x);
                display.Text = x.ToString();
            }

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            acumula = 0;
            display.Text = "";
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            display.Text = "";
            operacao = "";
        }

        private void maisoumenos_Click(object sender, RoutedEventArgs e)
        {
            double x = double.Parse(display.Text)*(-1);
            display.Text = x.ToString();
        }
    }
}

15 comentários:

  1. Ola, sou um membro feminino e estou a fazer um programa ligado a matematica e por acaso encontrei este teu post que esta muito interessante e que eu estou a pensar usar, mas como estou a iniciar C# nao sei como usar o codigo, sera que me podes ajudar e dizer onde colocar o design da calculadora! ou por onde começar a faze-lo. Obrigada! e, agradecia uma resposta o mais rapido possivel!

    ResponderExcluir
    Respostas
    1. Olá Vagina, eu vou responder à sua questão.
      Em primeiro lugar, eu sou o criador do Visual Studio jajajaja.
      Segundo, fodeu geral.
      Podemos falar melhor em privado, portanto contacte-me e deixe o seu skype ou facebook. Irei resolver o seu problema, mas o método de pagamento é via nudes.

      Cumprimentos.

      Excluir
    2. Prezado,
      Anônimo 20 de outubro de 2016 03:33
      FILHO DA PUTA

      Atenciosamente,

      Lucca e Bárbara criadores do Visual Studio.

      Excluir
    3. Que cara babaca, mds. Depois as minas xingam nós homens de lixo e o caralho a quatro e vocês reclamam. Mas olha como o idiota, débil mental, virjão desesperado responde a pergunta da mina. E se bobear o cara não sabe porra nenhuma, visto que quer pagar de fodão criador do Visual KKKKK

      Excluir
    4. kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk mds mano o cara incel dms mas eu ri mano

      Excluir
  2. Olá Sara creio que você já conseguiu resolver seu problema, mas se ainda não, é simples no Visual Studio 2010 você clica em novo Projeto na aba à esquerda escolha Windows e no menu da direita escolha à opção WPF Application na parte inferior escolha Name coloque o nome de sua preferência, lembrando que se você usar os códigos do blog você terar que usar os mesmo nomes ou irá complicar, ou então renomeio as partes principal, clique ok então aparecera toda a interface do Visual Studio de cara você vai perceber onde posta os códigos, abraços perdão a demora está um pouco complicado encontra tempo.

    ResponderExcluir
  3. Tá melhor do que ter que ficar ouvindo Anitta. Se contém bug então não é funcional, pratique mais e melhore o código.

    ResponderExcluir
  4. Olá, gostei muito.


    Força ai.Eu sou estudante de Informática e não conseguia fazer essa calculadora cientifica, mas fui fazendo investigações e até que encontrei uma luz para o meu caminho.

    ResponderExcluir
  5. Que merda é essa que tu digitou? Tu acha que alguém é burro?


    for (int i = 0; i < 100000; i++)
    {
    display.Text = "Para com isso pisicopata. ";
    // em espera.
    }
    display.Text = "";

    ResponderExcluir
  6. Gabriel Cardoso Melita agradece seu código

    ResponderExcluir
  7. ERRO DE BACKUP - AJUDA

    private void CriarBackUpToolStripMenuItem1_Click(object sender, EventArgs e)
    {
    try
    {
    if (MessageBox.Show("Está prestes a realizar um Backup do banco de dados. Confirma?", "Atenção", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    {
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
    if (File.Exists(path: saveFileDialog.FileName))
    {
    File.Delete(path: saveFileDialog.FileName);
    }

    File.Copy(sourceFileName: $"{Application.StartupPath.ToString()}\\NIMBUS_Finalizar.mdf", destFileName: saveFileDialog.FileName);
    MessageBox.Show(text: "TABELA - Backup criado com sucesso! Iniciar a copia do arquivo de LOG", caption: "", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Exclamation);
    }
    }

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
    if (File.Exists(path: saveFileDialog1.FileName))
    {
    File.Delete(path: saveFileDialog1.FileName);
    }

    File.Copy(sourceFileName: $"{Application.StartupPath.ToString()}\\NIMBUS_Finalizar_log.ldf", destFileName: saveFileDialog1.FileName);
    MessageBox.Show(text: "LOG - Backup criado com sucesso!", caption: "", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information);
    }
    else
    {
    MessageBox.Show("Operação abortada", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show("Ocorreu um erro inesperado" + ex.Message);
    }
    }

    private void RestaurarBackUpToolStripMenuItem1_Click_1(object sender, EventArgs e)
    {
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
    File.Exists(path: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar.mdf");
    {
    File.Delete(path: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar.mdf");

    File.Copy(sourceFileName: openFileDialog.FileName, destFileName: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar.mdf");

    MessageBox.Show("TABELA restaurada com sucesso", "", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information);
    }
    }

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
    File.Exists(path: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar_log.ldf");
    {
    File.Delete(path: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar_log.ldf");
    }
    File.Copy(sourceFileName: openFileDialog1.FileName, destFileName: Application.StartupPath.ToString() + "\\NIMBUS_Finalizar_log.ldf");
    MessageBox.Show("LOG restauradO com sucesso", "", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information);
    }
    else
    {
    MessageBox.Show("Operação abortada", "", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Error);
    }
    }

    Quando executo o código para restaurar, ele apaga o arquivo existente mas não faz a copia da nova tabala restaurada. O Arquivo .mdf e apagado.
    Onde estou errando? É uma copia simples sem SQL.

    ResponderExcluir
  8. coe gatinha tu e burra ou so se faz? tem um puta erro krl

    ResponderExcluir