C sharp - Menus y submenús con Windows Form simulando consola

 
Vista:
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Meta (122 intervenciones) el 28/03/2020 22:19:23
Hola:

Quiero hacer un menú y submenú indicado en el esquema de abajo. Es una plantilla simulando una consola de C#. Usa 4 label, como mucho es de 20 caracter máximo en cada label.

Se mueve solo pulsando con el ratón los botones Arriba, Abajo, Izquierda, Derecha y Enter. También si es posible, manejar dichos botones con las flecas del teclado si es posible.

Aquí abajo la apariencia del formulario.
captura-2110585

Aquí abajo el esquema general de como debe ser esos menú y submenús.

Ver zoom.

¿Cómo se hace?

Saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 373
Plata
Ha aumentado su posición en 2 puestos en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Agustin (171 intervenciones) el 29/03/2020 05:51:49
Yo partiría de una interfaz asi:

1
2
3
4
5
6
7
8
9
10
public interface IMenu
{
    IEnumerable<string> Render();
 
    void OnLeftKey();
    void OnRightKey();
    void OnUpKey();
    void OnDownKey();
    void OnEnterKey();
}

e iria implementando las distintas formas de menúes.

Por ejemplo, el menú principal, el A, el B1, el B2, y el SI, todos son la misma clase, que lo unico que hace es mostrar un texto y esperar que el usuario presione Enter para ir a otro lado.

Despues tenés el C1 que permite izquierda, derecha, y los demas que permiten arriba, abajo, enter.

Al final de todo, en el constructor del form, tenés que instanciar un grafo de objetos que definan todas las opciones y las relaciones entre ellas.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Meta (122 intervenciones) el 29/03/2020 16:01:39
Me acabas de partir en dos.

Lo he hecho de forma horrible en modo consola. Tiene muchos códigos repetidos, es muy largo y feo. Espero que en WindfowsForm sea mejor que este. Dejo el ejemplo para que lo entiendas.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
using System;
 
namespace Menu_consola_18_cs
{
    class Program
    {
        // Variable general para guardar el > de la última opción que haz entrado
        // en la hora de volver atrás. Por ejemplo:
        private static int guardarOpcion = 0;
        static void Main(string[] args)
        {
            Console.Title = "Menú de opciones";
 
            // Tamaño ventana consola.
            // X anchura.
            Console.WindowWidth = 20;
 
            // Y altura.
            Console.WindowHeight = 5;
 
            // Ocultar cursor.
            Console.CursorVisible = false;
 
            // Fondo verde.
            Console.BackgroundColor = ConsoleColor.Green;
 
            // Letras negras.
            Console.ForegroundColor = ConsoleColor.Black;
 
            MenuPrincipal();
        }
 
        #region Menú principal.
        public static void MenuPrincipal()
        {
            // Almacena la tecla pulsada en la variable.
            ConsoleKey teclaInicial;
 
            // Limpiar pantalla.
            Console.Clear();
 
            // Posición del cursor del título del MENÚ PRINCIPAL.
            Console.SetCursorPosition(0, 0);
 
            // Título.
            Console.Write("   MENÚ PRINCIPAL   ");
 
            // Pocisión de la hora.
            Console.SetCursorPosition(4, 2);
 
            // Formato numérico dd/MM/yyyy.
            Console.Write(DateTime.Now.ToString("ddd dd MMM"));
 
            // Almacena en la variable una tecla pulsada.
            teclaInicial = Console.ReadKey(true).Key;
 
            // ¿Haz pulsado la tecla Enter?
            if (teclaInicial == ConsoleKey.Enter)
            {
                // Sí. Se ejecuta esta función.
                MenuOpciones();
            }
        }
        #endregion
 
        #region Menú de opciones principales.
        public static void MenuOpciones()
        {
            // Contador de teclas y navegador.
            int opcion = 0;
            opcion = guardarOpcion;
 
            // Capturar tecla para luego validar.
            ConsoleKey tecla;
 
            while (true)
            {
                //******************************************************************
                // Dibujo el menú principal.
 
                // Limpiar pantalla.
                Console.Clear();
 
                switch (opcion)
                {
                    case 0:
                        Console.SetCursorPosition(0, 0);
                        Console.Write("> Opción A.         ");
                        Console.SetCursorPosition(0, 1);
                        Console.Write("  Opción B.         ");
                        Console.SetCursorPosition(0, 2);
                        Console.Write("  Opción C.         ");
                        Console.SetCursorPosition(0, 3);
                        Console.Write("  Salir.            ");
                        break;
                    case 1:
                        Console.SetCursorPosition(0, 0);
                        Console.Write("  Opción A.         ");
                        Console.SetCursorPosition(0, 1);
                        Console.Write("> Opción B.         ");
                        Console.SetCursorPosition(0, 2);
                        Console.Write("  Opción C.         ");
                        Console.SetCursorPosition(0, 3);
                        Console.Write("  Salir.            ");
                        break;
                    case 2:
                        Console.SetCursorPosition(0, 0);
                        Console.Write("  Opción A.         ");
                        Console.SetCursorPosition(0, 1);
                        Console.Write("  Opción B.         ");
                        Console.SetCursorPosition(0, 2);
                        Console.Write("> Opción C.         ");
                        Console.SetCursorPosition(0, 3);
                        Console.Write("  Salir.            ");
                        break;
                    case 3:
                        Console.SetCursorPosition(0, 0);
                        Console.Write("  Opción A.         ");
                        Console.SetCursorPosition(0, 1);
                        Console.Write("  Opción B.         ");
                        Console.SetCursorPosition(0, 2);
                        Console.Write("  Opción C.         ");
                        Console.SetCursorPosition(0, 3);
                        Console.Write("> Salir.            ");
                        break;
                    default:
                        Console.Write("Fuera de rango.     ");
                        break;
                }
 
                // Fin de pintar el menú principal.
                //******************************************************************
 
                // Leer tecla ingresada por el usuario.
                tecla = Console.ReadKey(true).Key;
 
                // Validar el tipo de tecla.
                if (tecla == ConsoleKey.Enter)
                {
                    switch (opcion)
                    {
                        case 0:
                            OpcionA();
                            break;
                        case 1:
                            OpcionB();
                            break;
                        case 2:
                            OpcionC();
                            break;
                        case 3:
                            guardarOpcion = 0;
                            MenuPrincipal();
                            break;
                        default:
                            break;
                    }
                }
 
                // Flecha abajo del teclado.
                if (tecla == ConsoleKey.DownArrow)
                {
                    opcion++;
                }
 
                // Flecha arriba del teclado.
                if (tecla == ConsoleKey.UpArrow)
                {
                    opcion--;
                }
 
                // Si está en la última opción del menú, salta a la primera.
                if (opcion > 3)
                {
                    opcion = 0;
                }
 
                // Si está en la primera posición del menú, salta a la última.
                if (opcion < 0)
                {
                    opcion = 3;
                }
            }
        }
        #endregion
 
        #region Opción A (0).
        public static void OpcionA()
        {
            ConsoleKey teclaOpcionA;
            Console.Clear();
            do
            {
                Console.SetCursorPosition(0, 0);
                Console.WriteLine("Estás en Opción A.");
                Console.SetCursorPosition(0, 2);
                Console.WriteLine("Pulse Enter para");
                Console.SetCursorPosition(0, 3);
                Console.WriteLine("Salir.");
 
                // Almacena el teclado pulsado en la variable teclaSubMenuA.
                teclaOpcionA = Console.ReadKey(true).Key;
 
            } while (teclaOpcionA != ConsoleKey.Enter);
        }
        #endregion
 
        #region Opción B (1).
        public static void OpcionB()
        {
            // Contador de teclas y navegador.
            int opcionB = 0;
 
            // Capturar tecla para luego validar.
            ConsoleKey teclaOpcionB;
 
            while (true)
            {
                switch (opcionB)
                {
                    case 0:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción B.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("> SubOpción B-1.    ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  SubOpción B-2     ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Salir.            ");
                        break;
                    case 1:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción B.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  SubOpción B-1.    ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("> SubOpción B-2     ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Salir.            ");
                        break;
                    case 2:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción B.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  SubOpción B-1.    ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  SubOpción B-2     ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("> Salir.            ");
                        break;
                    default:
                        Console.Write("Fuera de rango.     ");
                        break;
                }
 
                // Leer tecla ingresada por el usuario.
                teclaOpcionB = Console.ReadKey(true).Key;
 
                // Validar el tipo de tecla.
                if (teclaOpcionB == ConsoleKey.Enter)
                {
                    switch (opcionB)
                    {
                        case 0:
                            OpcionB1();
                            break;
                        case 1:
                            OpcionB2();
                            break;
                        case 2:
                            guardarOpcion = 1;
                            MenuOpciones();
                            break;
                        default:
                            Console.Write("Fuera de rango.     ");
                            break;
                    }
                }
 
                if (teclaOpcionB == ConsoleKey.DownArrow)
                {
                    opcionB++;
                }
 
                if (teclaOpcionB == ConsoleKey.UpArrow)
                {
                    opcionB--;
                }
 
                // Si está en la última opción, salta a la primera.
                if (opcionB > 2)
                {
                    opcionB = 0;
                }
 
                // Si está en la primera posición, salta a la última.
                if (opcionB < 0)
                {
                    opcionB = 2;
                }
            }
        }
 
        #endregion
 
        #region Opcion B-1.
        public static void OpcionB1()
        {
            ConsoleKey teclaOpcionB1;
            Console.Clear();
            do
            {
                Console.SetCursorPosition(0, 0);
                Console.WriteLine("Estás en Opción B-1.");
                Console.SetCursorPosition(0, 2);
                Console.WriteLine("Pulse Enter para    ");
                Console.SetCursorPosition(0, 3);
                Console.WriteLine("volver atrás.       ");
 
                // Almacena el teclado pulsado en la variable teclaSubMenuA.
                teclaOpcionB1 = Console.ReadKey(true).Key;
 
            } while (teclaOpcionB1 != ConsoleKey.Enter);
        }
        #endregion
 
        #region Opcion B-2.
        public static void OpcionB2()
        {
            ConsoleKey teclaOpcionB2;
            Console.Clear();
            do
            {
                Console.SetCursorPosition(0, 0);
                Console.WriteLine("Estás en Opción B-2.");
                Console.SetCursorPosition(0, 2);
                Console.WriteLine("Pulse Enter para    ");
                Console.SetCursorPosition(0, 3);
                Console.WriteLine("volver atrás.       ");
 
                // Almacena el teclado pulsado en la variable teclaSubMenuA.
                teclaOpcionB2 = Console.ReadKey(true).Key;
 
            } while (teclaOpcionB2 != ConsoleKey.Enter);
        }
        #endregion
 
        #region Opción C (2).
        public static void OpcionC()
        {
            // Contador de teclas y navegador.
            int opcionC = 0;
 
            // Capturar tecla para luego validar.
            ConsoleKey teclaOpcionC;
            Console.Clear();
 
            while(true)
            {
                switch (opcionC)
                {
                    case 0:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción C.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("> Color 1.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  Color 2.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Opción C-1.       ");
                        break;
                    case 1:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción C.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  Color 1.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("> Color 2.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Opción C-1.       ");
                        break;
                    case 2:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción C.  ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  Color 1.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  Color 2.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("> Opción C-1.       ");
                        break;
                    case 3:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("> Color 3.          ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  Color 4.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  Color 5.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Salir.            ");
                        break;
                    case 4:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("  Color 3.          ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("> Color 4.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  Color 5.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Salir.            ");
                        break;
                    case 5:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("  Color 3.          ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  Color 4.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("> Color 5.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("  Salir.            ");
                        break;
                    case 6:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("  Color 3.          ");
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("  Color 4.          ");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  Color 5.          ");
                        Console.SetCursorPosition(0, 3);
                        Console.WriteLine("> Salir.            ");
                        break;
 
                    default:
                        Console.Write("Fuera de rango.     ");
                        break;
                }
 
                // Leer tecla ingresada por el usuario.
                teclaOpcionC = Console.ReadKey(true).Key;
 
                // Validar el tipo de tecla.
                if (teclaOpcionC == ConsoleKey.Enter)
                {
                    switch (opcionC)
                    {
                        case 0:
                            // Fondo azul.
                            Console.BackgroundColor = ConsoleColor.Blue;
 
                            // Letras blancas.
                            Console.ForegroundColor = ConsoleColor.White;
                            break;
                        case 1:
                            // Fondo verde.
                            Console.BackgroundColor = ConsoleColor.Green;
 
                            // Letras negras.
                            Console.ForegroundColor = ConsoleColor.Black;
                            break;
                        case 2:
                            OpcionC1();
                            break;
                        case 3:
                            // Fondo negro.
                            Console.BackgroundColor = ConsoleColor.Black;
 
                            // Letras rojo.
                            Console.ForegroundColor = ConsoleColor.Red;
                            break;
                        case 4:
                            // Fondo negro.
                            Console.BackgroundColor = ConsoleColor.Black;
 
                            // Letras rojo.
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            break;
                        case 5:
                            // Fondo negro.
                            Console.BackgroundColor = ConsoleColor.Red;
 
                            // Letras rojo.
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            break;
                        case 6:
                            guardarOpcion = 2;
                            MenuOpciones();
                            break;
                        default:
                            Console.Write("Fuera de rango.     ");
                            break;
                    }
                }
 
                if (teclaOpcionC == ConsoleKey.DownArrow)
                {
                    opcionC++;
                }
 
                if (teclaOpcionC == ConsoleKey.UpArrow)
                {
                    opcionC--;
                }
 
                // Si está en la última opción, salta a la primera.
                if (opcionC > 6)
                {
                    opcionC = 0;
                }
 
                // Si está en la primera posición, salta a la última.
                if (opcionC < 0)
                {
                    opcionC = 6;
                }
            }
        }
        #endregion
 
        #region OpcionC-1.
        public static void OpcionC1()
        {
            // Contador de teclas y navegador.
            int opcionC1 = 0;
 
            // Capturar tecla para luego validar.
            ConsoleKey teclaOpcionC1;
            Console.Clear();
 
            while(true)
            {
                Console.Clear();
 
                switch (opcionC1)
                {
                    case 0:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción C-1.");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("  SI");
                        Console.SetCursorPosition(16, 2);
                        Console.WriteLine("> NO");
                        break;
                    case 1:
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("Estás en Opción C-1.");
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine("> SI");
                        Console.SetCursorPosition(16, 2);
                        Console.WriteLine("  NO");
                        break;
                    default:
                        Console.Write("Fuera de rango.     ");
                        break;
                }
 
                // Leer tecla ingresada por el usuario.
                teclaOpcionC1 = Console.ReadKey(true).Key;
 
                // Validar el tipo de tecla.
                if (teclaOpcionC1 == ConsoleKey.Enter)
                {
                    switch (opcionC1)
                    {
                        case 0:
                            guardarOpcion = 2;
                            MenuPrincipal();
                            //Console.Clear();
                            break;
                        case 1:
                            OpcionSI();
                            break;
                        default:
                            Console.Write("Fuera de rango.     ");
                            break;
                    }
                }
 
                // Flecha derecha.
                if (teclaOpcionC1 == ConsoleKey.RightArrow)
                {
                    opcionC1++;
                }
 
                // Flecha izquierda.
                if (teclaOpcionC1 == ConsoleKey.LeftArrow)
                {
                    opcionC1--;
                }
 
                // Si está en la última opción, salta a la primera.
                if (opcionC1 > 1)
                {
                    opcionC1 = 0;
                }
 
                // Si está en la primera posición, salta a la última.
                if (opcionC1 < 0)
                {
                    opcionC1 = 1;
                }
            }
        }
        #endregion
 
        #region opcionSI del sub menú C-1.
        public static void OpcionSI()
        {
            ConsoleKey teclaOpcionB1;
            Console.Clear();
            do
            {
                Console.SetCursorPosition(0, 0);
                Console.WriteLine("Estás en Opción SÍ.");
                Console.SetCursorPosition(0, 2);
                Console.WriteLine("Pulse Enter para    ");
                Console.SetCursorPosition(0, 3);
                Console.WriteLine("volver atrás.       ");
 
                // Almacena el teclado pulsado en la variable teclaOpciónB1.
                teclaOpcionB1 = Console.ReadKey(true).Key;
 
            } while (teclaOpcionB1 != ConsoleKey.Enter);
        }
        #endregion
    }
}

;)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 373
Plata
Ha aumentado su posición en 2 puestos en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Agustin (171 intervenciones) el 29/03/2020 21:40:15
Es que no se trata de si usas winforms o consola, se trata de usar OOP en lugar de programación procedimental, como hiciste.

O sea lo que yo planteo es modelar objetos que encapsulen comportamiento, para poder reutilizar ese comportamiento y no repetir código todo el tiempo.

De hecho como la interfaz que te propuse devuelve un IEnumerable<string>, podrias incluso usar los mismos objetos para winforms que para la consola, con un adaptador en el medio que sepa "imprimir" esos strings en cada caso.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Meta (122 intervenciones) el 30/03/2020 00:08:55
Buenas:

Lo que hice, es lo que me enseñó una persona ya mayor que dice que aprendió así en el MD-DOS, en aquella época.

Pues si, debo aprenderlo mucho mejor a objetos para que no me toque las narices.

Tengo intención de hacerlo de nuevo usando los textos de un menú colocarlo en un array, vector tipo string. Luego lo llamo para que genere el menú y las flecha indicadora de las opciones, solo cambian de coordenada. No quiero repetir codigos y códigos. Date cuanta que cada menú o submenú es un método. Pero el código se hace laaaaaaaaaaaaaaaargo y duro.

Saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Meta (122 intervenciones) el 30/03/2020 15:36:45
Hola:

¿Algo así?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace WinFormsAppMenus
{
    public partial class Form1 : Form
    {
        public Label[] labels = new Label[6];
        public Keys tecla;
        public static bool AnularTodosLosCiclos = false;
 
        public Form1()
        {
            InitializeComponent();
            for (int a = 0; a < labels.Length; a++)
                labels[a] = new Label();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            labels[0].Location = new Point(200, 40);
            labels[0].Text = "MENÚ PRINCIPAL";
            labels[0].AutoSize = true;
            labels[1].Location = new Point(200, 80);
            labels[1].Text = DateTime.Now.ToLongDateString();
            labels[1].AutoSize = true;
 
            Controls.AddRange(labels.ToArray());
 
            StartMenus();
        }
 
        private void StartMenus()
        {
            Menu principal = new Menu(this, -1, 200, 40, "MENÚ PRINCIPAL", new string[] { DateTime.Now.ToLongDateString() });
            Menu opciones = new Menu(this, 0, 200, 40, "", new string[] { "Opción A", "Opción B", "Opción C", "Salir" });
            Menu opcionA = new Menu(this, 0, 200, 40, "Estás en Opción A.", new string[] { "Pulsa Enter para Salir" });
            Menu opcionB = new Menu(this, 0, 200, 40, "Estás en Opción B.", new string[] { "SubOpción B-1.", "SubOpción B-2.", "Salir." });
            Menu opcionC = new Menu(this, 0, 200, 40, "Estás en Opción C.", new string[] { "Color 1", "Color 2", "Opción C-1." });
            Menu opcionC1 = new Menu(this, 1, 200, 40, "Estás en Opción C-1.", new string[] { "SI", "NO" });
            Menu opcionB1 = new Menu(this, 1, 200, 40, "Estás en Opción B-1.", new string[] { "Pulsa Enter para volver atrás." });
            Menu opcionB2 = new Menu(this, 1, 200, 40, "Estás en Opción B-2.", new string[] { "Pulsa Enter para volver atrás." });
            Menu opcionSi = new Menu(this, 1, 200, 40, "Estás en Opción SI.", new string[] { "Pulsa Enter para volver atrás." });
 
            int opcion;
            int goBack = 0;
            this.Visible = true;
 
            while (true)
            {
                this.BringToFront();
                Application.DoEvents();
                opcion = principal.DoMenu();
                if (Form1.AnularTodosLosCiclos == true)
                    break;
                if (opcion == 0)
                {
                    while (true)
                    {
                        this.BringToFront();
                        Application.DoEvents();
                        opcion = opciones.DoMenu();
                        if (Form1.AnularTodosLosCiclos == true)
                            break;
                        if (opcion == 0)
                        {
                            while (true)
                            {
                                this.BringToFront();
                                Application.DoEvents();
                                opcion = opcionA.DoMenu();
                                if (Form1.AnularTodosLosCiclos == true)
                                    break;
                                if (opcion == 0 || opcion == -3)
                                break;
                            }
                        }
                        else if (opcion == 1)
                        {
                            while (true)
                            {
                                this.BringToFront();
                                Application.DoEvents();
                                opcion = opcionB.DoMenu();
                                if (Form1.AnularTodosLosCiclos == true)
                                    break;
                                if (opcion == 0)
                                {
                                    while (true)
                                    {
                                        this.BringToFront();
                                        Application.DoEvents();
                                        opcion = opcionB1.DoMenu();
                                        if (Form1.AnularTodosLosCiclos == true)
                                            break;
                                        if (opcion == 0 || opcion == -3)
                                            break;
                                    }
                                }
                                else if (opcion == 1)
                                {
                                    while (true)
                                    {
                                        this.BringToFront();
                                        Application.DoEvents();
                                        opcion = opcionB2.DoMenu();
                                        if (Form1.AnularTodosLosCiclos == true)
                                            break;
                                        if (opcion == 0 || opcion == -3)
                                        break;
                                    }
                                }
                                else if (opcion == 2 || opcion == -3)
                                {
                                    break;
                                }
                            }
                        }
                        else if (opcion == 2)
                        {
                            while (true)
                            {
                                this.BringToFront();
                                Application.DoEvents();
                                opcion = opcionC.DoMenu();
                                if (Form1.AnularTodosLosCiclos == true)
                                    break;
                                if (opcion == 0)
                                {
                                    ;
                                }
                                else if (opcion == 1)
                                {
                                    ;
                                }
                                else if (opcion == 2)
                                {
                                    while (true)
                                    {
                                        this.BringToFront();
                                        Application.DoEvents();
                                        opcion = opcionC1.DoMenu();
                                        if (Form1.AnularTodosLosCiclos == true)
                                            break;
                                        if (opcion == 0)
                                        {
                                            while (true)
                                            {
                                                this.BringToFront();
                                                Application.DoEvents();
                                                opcion = opcionSi.DoMenu();
                                                if (opcion == 0)
                                                    break;
                                            }
                                        }
                                        else if (opcion == 1 || opcion == -3)
                                        {
                                            goBack = 2;
                                            break;
                                        }
                                    }
                                    if (goBack > 0)
                                    {
                                        goBack--;
                                        break;
                                    }
                                }
                                else if (opcion == -3)
                                {
                                    break;
                                }
                            }
                            if (goBack > 0)
                            {
                                goBack--;
                                break;
                            }
                        }
                        else if (opcion == 3 || opcion == -3)
                        {
                            break;
                        }
                    }
                }
            }
        }
 
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            tecla = e.KeyCode;
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Form1.AnularTodosLosCiclos = true;
        }
    }
 
    class Menu
    {
        private Form1 form;
        private int what;
        private string titulo;
        private string[] opciones;
        private int X, Y;
        private int Indice;
        private Label flecha;
        private Font fuente;
 
        public Menu(Form1 form, int what, int x, int y, string titulo, string[] opciones)
        {
            this.form = form;
            this.what = what;
            this.X = x;
            this.Y = y;
            this.titulo = titulo;
            this.opciones = opciones;
        }
 
        public int DoMenu()
        {
            int a;
            fuente = new Font("Microsoft Sans Serif", 16);
 
            foreach (Label label in form.labels)
                label.Visible = false;
 
            form.labels[5].Font = fuente;
            form.labels[5].AutoSize = true;
            form.labels[5].Text = this.titulo;
            form.labels[5].Location = new Point(200, 10);
            form.labels[5].Visible = true;
 
            if (what == 0 || what == -1)
            {
                for (a = 0; a < opciones.Length; a++)
                {
                    form.labels[a].Visible = true;
                    form.labels[a].Location = new Point(X, Y + a * 40);
                    form.labels[a].AutoSize = true;
                    form.labels[a].Font = fuente;
                    form.labels[a].Text = opciones[a];
                }
            }
            else if (what == 1)
            {
                for (a = 0; a < opciones.Length; a++)
                {
                    form.labels[a].Visible = true;
                    form.labels[a].Location = new Point(X + a * 120, Y);
                    form.labels[a].AutoSize = true;
                    form.labels[a].Font = fuente;
                    form.labels[a].Text = opciones[a];
                }
            }
 
            flecha = new Label();
            flecha.Font = fuente;
            flecha.Text = ">";
            form.Controls.Add(flecha);
            flecha.Visible = false;
            if (what >= 0)
            {
                flecha.Visible = true;
            }
 
            while (true)
            {
                form.BringToFront();
                Application.DoEvents();
 
                if (Form1.AnularTodosLosCiclos == true)
                    return -7;
 
                if (((form.tecla == Keys.Up && what == 0) || (form.tecla == Keys.Left && what == 1)) && Indice > 0)
                {
                    form.tecla = 0;
                    Indice--;
                }
                else if (((form.tecla == Keys.Down && what == 0) || (form.tecla == Keys.Right && what == 1)) && Indice < opciones.Length - 1)
                {
                    Indice++;
                    form.tecla = 0;
                }
                else if (form.tecla == Keys.Escape)
                {
                    form.tecla = 0;
                    flecha.Visible = false;
                    return -3;
                }
                else if (form.tecla == Keys.Return)
                {
                    form.tecla = 0;
                    flecha.Visible = false;
                    return Indice;
                }
 
                if (what == 0)
                    flecha.Location = new Point(X - 15, Y + Indice * 40);
                else if (what == 1)
                    flecha.Location = new Point(X - 15 + Indice * 120, Y);
            }
        }
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 373
Plata
Ha aumentado su posición en 2 puestos en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Agustin (171 intervenciones) el 30/03/2020 15:53:12
Mmmmm.... no.

Estas mezclando la lógica con la capa de presentación, y es super importante que esto esté bien separado.

Además, usás muchísimos números mágicos que entendés vos solo. O sea if (what == 1) no tengo idea qué es.
Ponele nombres claros a las cosas, y reemplazá los números mágicos por enums o constantes.

Igual ahí hay un problema más de fondo que es la separación. Apenas tenga un tiempo te armo un ejemplo.

Otra cosa: Application.DoEvents() es un pecado mortal. Tenés que leer sobre threading y entender por qué se cuelga la aplicación cuando sacas eso. Luego sacarlo y usar los mecanismos que corresponden
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Menus y submenús con Windows Form simulando consola

Publicado por Meta (122 intervenciones) el 30/03/2020 17:19:16
Este programa no lo he hecho yo.

Tampoco lo entiendo bien. Ya le envié tu mensaje a ver que tal.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar