How to make the console output appear in a textarea in Windowsforms?

Asked

Viewed 52 times

1

I would like to know a way in which the output of my project, appear in a textarea in Windowsforms. I need this because my system is a binary number converter, and I want you to print out the step-by-step calculation on the screen. If there is another way, I accept suggestions!

Method example:

public int ConverterDeBinarioParaDecimal(String numeroBinario)
    {
        double resultado = 0;
        int qtdDigitos = numeroBinario.Length;
        Console.WriteLine("xxx = {0}", qtdDigitos);

        for (int cont = 0; cont < qtdDigitos; cont++)
        {
            if (numeroBinario[cont] == '1')
            {
                resultado = resultado + Math.Pow(2, qtdDigitos - (cont + 1));

            }
        }

        int resultadoConversao = Convert.ToInt32(resultado);

        return resultadoConversao;
    }
  • What’s wrong with replacing Console.WriteLine for MessageBox.Show or TextBox1.Text ? Since it is windows Forms it makes sense to use the appropriate things in this context. Console, as its name implies, it is for console mode applications.

1 answer

1

A console only displays the executable log, it would be complicated to redirect the output of the Console stream to a Textbox (this is not impossible, but boring). There’s a simple line of code that allows you to do the same thing:

public static void WriteLn (string text, params string[] args)
    => TextBox1.Text += "\n" + String.Format(text, args);
public static void WriteLn (string text)
    => WriteLn (text, new string[] { });

To use, just replace

Console.WriteLine("xxx = {0}", qtdDigitos);

for:

WriteLn("xxx = {0}", qtdDigitos);

Note: Change the control name TextBox1 if necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.