Example.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // This is a simple example application. For the full range of functionality
  2. // see the UICatalog project
  3. // A simple Terminal.Gui example in C# - using C# 9.0 Top-level statements
  4. using System;
  5. using Terminal.Gui;
  6. // Override the default configuration for the application to use the Light theme
  7. ConfigurationManager.RuntimeConfig = """{ "Theme": "Light" }""";
  8. Application.Run<ExampleWindow> ().Dispose ();
  9. // Before the application exits, reset Terminal.Gui for clean shutdown
  10. Application.Shutdown ();
  11. // To see this output on the screen it must be done after shutdown,
  12. // which restores the previous screen.
  13. Console.WriteLine ($@"Username: {ExampleWindow.UserName}");
  14. // Defines a top-level window with border and title
  15. public class ExampleWindow : Window
  16. {
  17. public static string UserName;
  18. public ExampleWindow ()
  19. {
  20. Title = $"Example App ({Application.QuitKey} to quit)";
  21. // Create input components and labels
  22. var usernameLabel = new Label { Text = "Username:" };
  23. var userNameText = new TextField
  24. {
  25. // Position text field adjacent to the label
  26. X = Pos.Right (usernameLabel) + 1,
  27. // Fill remaining horizontal space
  28. Width = Dim.Fill ()
  29. };
  30. var passwordLabel = new Label
  31. {
  32. Text = "Password:", X = Pos.Left (usernameLabel), Y = Pos.Bottom (usernameLabel) + 1
  33. };
  34. var passwordText = new TextField
  35. {
  36. Secret = true,
  37. // align with the text box above
  38. X = Pos.Left (userNameText),
  39. Y = Pos.Top (passwordLabel),
  40. Width = Dim.Fill ()
  41. };
  42. // Create login button
  43. var btnLogin = new Button
  44. {
  45. Text = "Login",
  46. Y = Pos.Bottom (passwordLabel) + 1,
  47. // center the login button horizontally
  48. X = Pos.Center (),
  49. IsDefault = true
  50. };
  51. // When login button is clicked display a message popup
  52. btnLogin.Accepting += (s, e) =>
  53. {
  54. if (userNameText.Text == "admin" && passwordText.Text == "password")
  55. {
  56. MessageBox.Query ("Logging In", "Login Successful", "Ok");
  57. UserName = userNameText.Text;
  58. Application.RequestStop ();
  59. }
  60. else
  61. {
  62. MessageBox.ErrorQuery ("Logging In", "Incorrect username or password", "Ok");
  63. }
  64. // Anytime Accepting is handled, make sure to set e.Cancel to false.
  65. e.Cancel = false;
  66. };
  67. // Add the views to the Window
  68. Add (usernameLabel, userNameText, passwordLabel, passwordText, btnLogin);
  69. }
  70. }