2012-10-11 49 views
5

Tengo un problema con el centrado de texto en una aplicación de consola C# .NET4.Texto de centrado en la aplicación de consola C# solo funciona con alguna entrada

Este es mi método para centrar el texto:

private static void centerText(String text) 
{ 
    int winWidth = (Console.WindowWidth/2); 
    Console.WriteLine(String.Format("{0,"+winWidth+"}", text)); 
} 

Sin embargo, apenas consigo la salida, ya que habría sido emitida normalmente. Sin embargo, si yo uso esta línea:

Console.WriteLine(String.Format("{0,"+winWidth+"}", "text")); 

El "texto" consigue centrado como debería.

Estoy llamando centerText con estos dos métodos:

private static void drawStars() 
{ 
    centerText("*********************************************"); 
} 
private static void title(string location) 
{ 
    drawStars(); 
    centerText("+++ Du er nu her: " + location + "! +++"); 
    drawStars(); 
} 
+0

El problema se produce cuando/porque el texto es más largo que la mitad del ancho de la pantalla. – DaveShaw

+0

@DaveShaw Existe un problema mayor: el ancho del texto nunca fue parte del centrado. –

Respuesta

10

probar este lugar:

private static void centerText(String text) 
{ 
    Console.Write(new string(' ', (Console.WindowWidth - text.Length)/2)); 
    Console.WriteLine(text); 
} 

El problema con el código inicial era que su texto se inicia en el centro de la pantalla. Quieres que el centro del texto esté allí.

Va a hacer un poco más de trabajo si desea imprimir párrafos enteros centrados como este.

+0

¡Gracias! ¡Funciona de maravilla! –

1

El texto aprobado en el pueden tener espacios en blanco como \r\n, a continuación, quitar que antes de llamar a la escritura como

string textClean = Regex.Replace(text, @"([\r\n])", string.Empty); 

// Then center on text clean 
+0

Si bien este es un buen consejo, aquí no parece ser el problema de raíz. Por lo tanto, esto debería ser solo un comentario. – Servy

0

tengo mi propio método para llamar cabeceras de consola:

public static void Header(string title, string subtitle = "", ConsoleColor color = ConsoleColor.White) 
{ 
    int windowWidth = 90 - 2; 
    string titleContent = String.Format("║{0," + ((windowWidth/2) + (title.Length/2)) + "}{1," + (windowWidth - (windowWidth/2) - (title.Length/2) + 1) + "}", title, "║"); 
    string subtitleContent = String.Format("║{0," + ((windowWidth/2) + (subtitle.Length/2)) + "}{1," + (windowWidth - (windowWidth/2) - (subtitle.Length/2) + 1) + "}", subtitle, "║"); 

    Console.WriteLine("╔════════════════════════════════════════════════════════════════════════════════════════╗"); 
    Console.WriteLine(titleContent); 
    if (!string.IsNullOrEmpty(subtitle)) 
    { 
     Console.WriteLine(subtitleContent); 
    } 
    Console.WriteLine("╚════════════════════════════════════════════════════════════════════════════════════════╝"); 
} 

A continuación, llámalo así YourStaticClass.Header("Test", "Version 1.0");

debería ser así:

╔════════════════════════════════════════════════════════════════════════════════════════╗ 
║           Test           ║ 
║          Version 1.0          ║ 
╚════════════════════════════════════════════════════════════════════════════════════════╝ 

Puede reemplazar el 90 en windowsWidth con Console.WindowWidth

Cuestiones relacionadas