elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Tutorial básico de Quickjs


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] Plantilla aplicación de consola con menú interactivo.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] Plantilla aplicación de consola con menú interactivo.  (Leído 1,721 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.821



Ver Perfil
[APORTE] Plantilla aplicación de consola con menú interactivo.
« en: 5 Diciembre 2013, 19:27 pm »

Quiero compartir mi plantilla de aplicación de consola por defecto con menú,
para importar la plantilla a VisualStudio símplemente deben copiar el archivo ZIP al directorio "...Mis Documentos\Visual Studio\Templates\ProjectTemplates\"  (o donde lo hayan establecido en la configuración de VisualStudio).

Esto es lo que le añadí:

· Menú inteligente, se mueve con las flechas de dirección del teclado, así como poder elegir una opción según el Identificador del item (1-9, A-Z).
· Sección de ayuda. (Logo, sintaxis, título)
· Método para escribir texto coloreado.
· Método para ocultar la consola.
· Método para lanzar un error conocido.

Todo documentado y en no muchas lineas de código.

Descarga: http://elektrostudios.tk/ElektroStudios%20Console%20Menu%20Application.zip



Una imagen:




Este es el código principal, junto a 2 Classes adicionales que se encuentran dentro de la plantilla.

Código
  1. Module Main
  2.  
  3. #Region " Variables "
  4.  
  5.    ''' <summary>
  6.    ''' The chooseable menu items.
  7.    ''' </summary>
  8.    Private ReadOnly MenuItems() As String =
  9.        {
  10.         "[1] One",
  11.         "[2] Two",
  12.         "[3] Three",
  13.         "[4] Four",
  14.         "[H] Help",
  15.         "[X] Exit"
  16.        }
  17.  
  18.    ''' <summary>
  19.    ''' Indicates the selected menu item.
  20.    ''' </summary>
  21.    Private CurrentMenuItem As Short = 0
  22.  
  23.    ''' <summary>
  24.    ''' The object to read in a pressed key.
  25.    ''' </summary>
  26.    Private key As ConsoleKeyInfo = Nothing
  27.  
  28.    ''' <summary>
  29.    ''' Indicates wether the user pressed a valid key.
  30.    ''' </summary>
  31.    Private ValidKeyIsPressed As Boolean = False
  32.  
  33.    ''' <summary>
  34.    ''' To manage known errors.
  35.    ''' </summary>
  36.    Private ReadOnly KnownErrors As New Dictionary(Of Integer, String) From
  37.    {
  38.        {1, "Wrong parameter"},
  39.        {2, "Parameter not specified"},
  40.        {9999, "Unknown Error"}
  41.    }
  42.  
  43. #End Region
  44.  
  45. #Region " Main Procedure "
  46.  
  47.    ''' <summary>
  48.    ''' The main procedure of this application.
  49.    ''' </summary>
  50.    Public Sub Main()
  51.        Console.Title = HelpSection.Title ' Set the Console Title.
  52.        ShowMenu() ' Display the console menu.
  53.        DoSomething()
  54.        Environment.Exit(0) ' Exit succesfully.
  55.    End Sub
  56.  
  57. #End Region
  58.  
  59. #Region " Methods "
  60.  
  61.    ''' <summary>
  62.    ''' Displays the console menu.
  63.    ''' </summary>
  64.    Private Sub ShowMenu()
  65.  
  66.        ' Wait for a valid key.
  67.        Do Until ValidKeyIsPressed
  68.  
  69.            ' Clear the screen.
  70.            Console.Clear()
  71.  
  72.            ' Print the application Logotype.
  73.            Write_Colored_Text(HelpSection.Logo, True, ConsoleColor.Green) ' Print the Logo.
  74.  
  75.            ' Print a simple help text.
  76.            Write_Colored_Text("[+] Choose an option:", True, ConsoleColor.White)
  77.            Console.WriteLine()
  78.  
  79.            ' Loop through all of the menu items to print them.
  80.            For Each MenuItem As String In MenuItems
  81.  
  82.                If MenuItem = MenuItems.ElementAt(CurrentMenuItem) Then
  83.                    Write_Colored_Text(String.Format(" -> {0}", MenuItem), True, ConsoleColor.Green)
  84.                Else
  85.                    Write_Colored_Text(MenuItem, True, ConsoleColor.Gray)
  86.                End If
  87.  
  88.            Next MenuItem
  89.  
  90.            ' Waits until the user presses a key.
  91.            key = Console.ReadKey(True)
  92.  
  93.            ' Process the pressed key.
  94.            Select Case key.Key
  95.  
  96.                Case Keys.Down ' If the key the user pressed is a "DownArrow", the current menu item will deacrease.
  97.                    CurrentMenuItem += 1
  98.                    If CurrentMenuItem > MenuItems.Length - 1 Then
  99.                        CurrentMenuItem = 0
  100.                    End If
  101.  
  102.                Case Keys.Up ' If the key the user pressed is a "UpArrow", the current menu item will increase.
  103.                    CurrentMenuItem -= 1
  104.                    If CurrentMenuItem < 0 Then
  105.                        CurrentMenuItem = CShort(MenuItems.Length - 1)
  106.                    End If
  107.  
  108.                Case Keys.Enter ' Enter Key (Select current menu item).
  109.                    ValidKeyIsPressed = True
  110.  
  111.                Case Keys.D1 To Keys.D4 ' A numeric key is pressed between 1-4.
  112.                    CurrentMenuItem = key.Key.ToString.Substring(1) - 1
  113.                    ValidKeyIsPressed = True
  114.  
  115.                Case Keys.H ' H Key (Print Help).
  116.                    PrintHelp()
  117.                    ValidKeyIsPressed = True
  118.  
  119.                Case Keys.X ' X Key (Exit from application).
  120.                    Environment.Exit(0)
  121.  
  122.            End Select
  123.  
  124.        Loop
  125.  
  126.    End Sub
  127.  
  128.    ''' <summary>
  129.    ''' Do something.
  130.    ''' </summary>
  131.    Private Sub DoSomething()
  132.        Console.WriteLine()
  133.        Write_Colored_Text("User Pressed Key: " & key.Key.ToString, True, ConsoleColor.Red, ConsoleColor.White)
  134.        Write_Colored_Text("Selected Option : " & MenuItems(CurrentMenuItem), True, ConsoleColor.Red, ConsoleColor.White)
  135.        Write_Colored_Text("Selected Index  : " & CurrentMenuItem.ToString, True, ConsoleColor.Red, ConsoleColor.White)
  136.        Console.ReadLine()
  137.    End Sub
  138.  
  139. #End Region
  140.  
  141. #Region " Miscellaneous Methods "
  142.  
  143.    ''' <summary>
  144.    ''' Writes colored text on the Console.
  145.    ''' </summary>
  146.    ''' <param name="Text">Indicates the text to write.</param>
  147.    ''' <param name="AddNewLine">Adds an empty line at the end of the text.</param>
  148.    ''' <param name="ForeColor">Indicates the text color.</param>
  149.    ''' <param name="BackColor">Indicates the background color.</param>
  150.    Private Sub Write_Colored_Text(ByVal Text As String,
  151.                                   Optional ByVal AddNewLine As Boolean = False,
  152.                                   Optional ByVal ForeColor As ConsoleColor = Nothing,
  153.                                   Optional ByVal BackColor As ConsoleColor = Nothing)
  154.  
  155.        Dim CurrentForegroundColor As ConsoleColor = Console.ForegroundColor
  156.        Dim CurrentBackgroundColor As ConsoleColor = Console.BackgroundColor
  157.  
  158.        Console.ForegroundColor = If(ForeColor = Nothing, CurrentForegroundColor, ForeColor)
  159.        Console.BackgroundColor = If(ForeColor = Nothing, CurrentBackgroundColor, BackColor)
  160.  
  161.        If AddNewLine Then
  162.            Console.WriteLine(Text)
  163.        Else
  164.            Console.Write(Text)
  165.        End If
  166.  
  167.        Console.ForegroundColor = CurrentForegroundColor
  168.        Console.BackgroundColor = CurrentBackgroundColor
  169.  
  170.    End Sub
  171.  
  172.    ''' <summary>
  173.    ''' Set the window state of the console.
  174.    ''' </summary>
  175.    ''' <param name="WindowState">Indicates the new state of the console window.</param>
  176.    Public Function SetWindow(ByVal WindowState As ConsoleWindowState.WindowState) As Boolean
  177.        Return ConsoleWindowState.SetWindowState(WindowState)
  178.    End Function
  179.  
  180.    ''' <summary>
  181.    ''' Print the Help section and exits from the application.
  182.    ''' </summary>
  183.    Private Sub PrintHelp()
  184.        Console.WriteLine(HelpSection.Help)
  185.        Environment.Exit(0) ' Exit succesfully.
  186.    End Sub
  187.  
  188.    ''' <summary>
  189.    ''' Launch a known error and exits from the application.
  190.    ''' </summary>
  191.    ''' <param name="ErrorID">
  192.    ''' Indicates the known Error Identifier.
  193.    ''' This value is also used to specify the ExitCode.
  194.    ''' </param>
  195.    ''' <param name="MoreInfo">Indicates additional information.</param>
  196.    Private Sub LaunchError(ByVal ErrorID As Integer, Optional ByVal MoreInfo As String = Nothing)
  197.  
  198.        Console.WriteLine()
  199.        Write_Colored_Text(KnownErrors(ErrorID) &
  200.                           If(MoreInfo IsNot Nothing, ": " & MoreInfo, Nothing),
  201.                           True, ConsoleColor.White, ConsoleColor.DarkRed)
  202.  
  203.        Environment.Exit(ErrorID) ' Exit with error exitcode.
  204.  
  205.    End Sub
  206.  
  207. #End Region
  208.  
  209. End Module

Saludos.


« Última modificación: 5 Diciembre 2013, 19:30 pm por EleKtro H@cker » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines