WPF - Conversor Numérico :  Decimal, Hexadecimal e Binário


Hoje vou apresentar um programa WPF que atua como um conversor numérico entre números decimais, hexadecimais e binários.

A ideía é bem simples...

Vamos criar um programa WPF com uma interface que exibe 3 TextBox. O primeiro corresponde a entrada de números decimais e a medida que o usuário digita a conversão para hexadecimal e binário é exibida nos outros dois TextBox da interface

Abra o VS 2017 Community e crie um novo projeto usando a linguagem C# do tipo Windows Desktop escolhendo o template WPF App(.NET Framework) com o nome WPF_ConversorNumerico

Inclua a partir da ToolBox os seguintes controles na MainWindow.xaml :

Disponha os controles conforme o leiaute da figura abaixo:

O código XAML gerado é o seguinte:

<Window x:Class="WPF_ConversorNumerico.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Conversor Numérico" Height="300" Width="525"
        Background="AliceBlue" FontSize="18" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" SizeToContent="Manual">
  <Window.Resources>
    <Style TargetType="TextBox">
      <Setter Property="Margin" Value="9 0 5 0" />
      <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
    <Style TargetType="TextBlock">
      <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
    <Style TargetType="Button">
      <Setter Property="Margin" Value="8 0 5 0" />
      <Setter Property="Padding" Value="7 2 7 2" />
      <Setter Property="VerticalAlignment" Value = "Center" />
    </Style>
  </Window.Resources>
  <Grid Margin="10">
    <Grid.RowDefinitions>
      <RowDefinition />
      <RowDefinition />
      <RowDefinition />
      <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBlock Text="Decimal" Grid.Column="0" Grid.Row="0" />
    <TextBlock Text="Hexadecimal" Grid.Column="0" Grid.Row="1" />
    <TextBlock Text="Binário" Grid.Column="0" Grid.Row="2" />
    <TextBox Name="txtDecimal" Grid.Column="1" Grid.Row="0" TextChanged="txtDecimal_TextChanged" PreviewTextInput="txtDecimal_PreviewTextInput" />
    <TextBox Name="txtHexadecimal" Grid.Column="1" Grid.Row="1" TextChanged="txtHexadecimal_TextChanged" PreviewTextInput="txtHexadecimal_PreviewTextInput" />
    <TextBox Name="txtBinary" Grid.Column="1" Grid.Row="2" TextChanged="txtBinary_TextChanged" PreviewTextInput="txtBinary_PreviewTextInput" />
    <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="4">
      <Button Name="btnLimpar" Content="Limpar" Click="btnLimpar_Click" />
      <Button Name="btnFechar" Content="Fechar" Click="btnFechar_Click" />
    </StackPanel>
  </Grid>
</Window>

Note que estamos usando os eventos TextChanged e PrevieweTextInput que ocorre quando o TextBox obtém texto de maneira independente do dispositivo.

O evento PreviewTextInput permite que um componente ou aplicativo escute a entrada de texto de maneira independente do dispositivo. O teclado é o principal meio de PreviewTextInput; mas voz, manuscrito e outros dispositivos de entrada também podem gerar o PreviewTextInput.

Devido às combinações de teclas - nos teclados padrão ou nos editores de método de entrada - vários eventos de chave podem gerar apenas um evento de entrada de texto.

Abra o arquivo MainWindow.xaml.cs e inclua o código abaixo que vai fazer a conversão númerica tratando os eventos citados acima:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WPF_ConversorNumerico
{
  public partial class MainWindow : Window
  {
    bool alteracao = false; // usada quando o textbox for alterada a partir do codigo

    public MainWindow()
    {
      InitializeComponent ();
    }
    private void txtDecimal_TextChanged(object sender, TextChangedEventArgs e)
    {
      if (txtDecimal.Text == "")
      {
        txtBinary.Clear ();
        txtHexadecimal.Clear ();
        return;
      }
      if (alteracao)
        return;

     alteracao = true;
      try
      {
        long numero = Convert.ToInt64 (txtDecimal.Text, 10);
        txtHexadecimal.Text = Convert.ToString (numero, 16).ToUpper ();
        txtBinary.Text = Convert.ToString (numero, 2);     
      }
      catch (Exception ex)
      {
        MessageBox.Show (ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
      }
      alteracao = false;
    }
    private void txtHexadecimal_TextChanged(object sender, TextChangedEventArgs e)
    {
      if (txtHexadecimal.Text == "")
      {
        txtBinary.Clear ();
        txtDecimal.Clear ();
        return;
      }
      if (alteracao)
        return;      
      alteracao = true;
      try
      {
         long numero = Convert.ToInt64 (txtHexadecimal.Text, 16);
        txtDecimal.Text = numero.ToString ();
        txtBinary.Text = Convert.ToString (numero, 2);
      }
      catch (Exception ex)
      {
        MessageBox.Show (ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
      }
      alteracao = false;
    }
    private void txtBinary_TextChanged(object sender, TextChangedEventArgs e)
    {
      if (txtBinary.Text == "")
      {
        txtDecimal.Clear ();
        txtHexadecimal.Clear ();
        return;
      }
      if (alteracao)
        return;      
      alteracao = true;
      try
      {
        long numero = Convert.ToInt64 (txtBinary.Text, 2);
        txtDecimal.Text = numero.ToString ();
        txtHexadecimal.Text = numero.ToString ("X");
      }
      catch (Exception ex)
      {
        MessageBox.Show (ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
      }
      alteracao = false;
    }
    private void btnLimpar_Click(object sender, RoutedEventArgs e)
    {
      txtBinary.Text = txtDecimal.Text = txtHexadecimal.Text = "";
    }
    private void btnFechar_Click(object sender, RoutedEventArgs e)
    {
      Close ();
    }
    private void txtDecimal_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
      if (!Number.IsInteger(e.Text))
      {
        e.Handled = true;
      }
    }
    private void txtHexadecimal_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
      if (!Number.IsHexadecimal (e.Text))
      {
        e.Handled = true;
      }
    }
    private void txtBinary_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
      if (!Number.IsBinary (e.Text))
      {
        e.Handled = true;
      }
    }
  }
}

O código, apesar de um pouco extenso, é bem simples. A conversão númerica é feita no evento TextChanged.

O código também uma classe Numero para verificar o tipo da entrada do usuário.

public static class Numero
{
  public static bool IsInteger(string txt)
  {
    int output;
    return int.TryParse (txt, out output);
  }
  public static bool IsBinary(string s)
  {
    foreach (char ch in s)
      if (ch != '1' && ch != '0')
        return false;
    return true;
  }
  public static bool IsHexadecimal(string s)
  {
    const string hexdigits = "0123456789aAbBcCdDeEfF";
    foreach (char ch in s)
      if (hexdigits.IndexOf (ch) == -1)
        return false;
    return true;
  }
}

Executando o projeto iremos obter o seguinte resultado:

Pegue o projeto completo aqui :  WPF_Conversor.zip

Veja os Destaques e novidades do SUPER DVD Visual Basic (sempre atualizado) : clique e confira !

Quer migrar para o VB .NET ?

Quer aprender C# ??

Quer aprender os conceitos da Programação Orientada a objetos ?

Quer aprender o gerar relatórios com o ReportViewer no VS 2013 ?

Quer aprender a criar aplicações Web Dinâmicas usando a ASP .NET MVC 5 ?

Referências:


José Carlos Macoratti