No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

GUI : Ajouter un menu

Nous allons ajouter un menu à notre fenêtre, pour ouvrir une fenêtre de sélection de fichier (file browser).

Comme nous avons à notre disposition l'IDE Visual Studio, ne nous en privons pas. Nous pouvons simplement ajouter un composant ToolStrip en le sélectionnant dans la boite d'outils et en le déposant dans la fenêtre à l'aide de la souris (drag and drop).

Ensuite, nous pouvons cliquer sur le composant en mode design et sélectionner l'option DropDownButton.

Nous pouvons entrer le texte de la liste (dans notre cas File), puis cliquer sur le premier élément de la liste et entrer le texte de l'option (dans notre cas Open...).

Par défaut, les éléments sont représentés sous la forme d'images. Nous pouvons spécifier que nous désirons les afficher sous forme de texte en effectuant un clic droit sur un élément et sélectionner dans le groupe DisplayStyle l'option Text. Nous avons à notre disposition les options suivantes : None, Text, Image, ImageAndText.

Je sais que cela peut sembler stupide de déclarer une option et de la rendre invisible, mais dans certains cas cela peut se révéler plus pratique de seulement jouer sur une de ses propriétés pour la rendre visible que de la créer.

Pour associer une action à l'évènement généré par un clic sur l'option, il nous suffit de double cliquer sur l'option en mode design, et une fenêtre s'ouvre alors à nous avec cette partie de code qui nous intéresse :

  1. private void fileToolStripMenuItem_Click(object sender, EventArgs e)
  2. {
  3. }

Nous allons donc commencer à mettre les mains dans le cambouis... Nous allons maintenant spécifier que dans ce cas une fenêtre de sélection de fichier doit apparaître.

Petite astuce : Nous pouvons commencer à introduire le début des noms de classes ou de méthodes que nous désirons utiliser, puis utiliser la combinaison de touches [Shift] + [Space] (les touches majuscules et barre d'espace) qui active les propositions automatiques (auto complete).

  1. private void fileToolStripMenuItem_Click(object sender, EventArgs e)
  2. {
  3. OpenFileDialog openFileDialog = new OpenFileDialog();
  4. openFileDialog.ShowDialog();
  5. }

Pour vérifier que la boîte de sélection de fichier effectue bien ce que nous en attendons, nous allons placer dans notre fenêtre un composant qui nous permet d'afficher du texte. Comme pour notre ToolStrip, nous allons sélectionner dans l'onglet Toolbox le composant Label, et le déposer dans notre fenêtre en mode édition. Nous pouvons supprimer le texte, et dans l'onglet de propriétés, nous pouvons renommer le composant en filePathLabel (nom utilisé dans le code pour cette instance de Label), et affecter la valeur false à la propriété Visible.

  1. //Dans les déclarations de variables de la classe Form1
  2. private System.Windows.Forms.Label filePathLabel;
  3. //Dans la méthode InitializeComponent() de la classe Form1
  4. this.filePathLabel.AutoSize = true;
  5. this.filePathLabel.Location = new System.Drawing.Point(12, 40);
  6. this.filePathLabel.Name = "filePathLabel";
  7. this.filePathLabel.Size = new System.Drawing.Size(0, 13);
  8. this.filePathLabel.TabIndex = 1;
  9. this.filePathLabel.Visible = false;

Nous allons maintenant modifier le code correspondant à l'évènement du clic sur le menu, pour que non seulement il ouvre une fenêtre de sélection de fichier, mais qu'en plus il place le nom du fichier sélectionné dans la zone de texte que nous venons de créer, et que cette zone soit visible.

  1. private void fileToolStripMenuItem_Click(object sender, EventArgs e)
  2. {
  3. //Déclaration et initialisation de notre fenêtre de sélection de fichiers
  4. OpenFileDialog openFileDialog = new OpenFileDialog();
  5. //Affichage de la fenêtre
  6. openFileDialog.ShowDialog();
  7. //Affectation du label avec le chemin du fichier sélectionné;
  8. filePathLabel.Text = openFileDialog.FileName;
  9. //Affichage du label
  10. filePathLabel.Visible = true;
  11. }

Refactoring

Notre programme fonctionne, mais nous pouvons le modifier légèrement pour que le code soit plus facile à comprendre.

Nous allons déplacer la déclaration de la variable openFileDialog pour que sa portée ne se limite pas à la méthode. De cette manière, nous pouvons l'utiliser dans d'autres méthodes, et par exemple déplacer le code qui affichait le chemin, pour en faire une nouvelle méthode à part.

  1. private void fileToolStripMenuItem_Click(object sender, EventArgs e)
  2. {
  3. openFileDialog.ShowDialog();
  4. fillAndDisplayPathLabel();
  5. }
  6. private void fillAndDisplayPathLabel()
  7. {
  8. filePathLabel.Text = openFileDialog.FileName;
  9. filePathLabel.Visible = true;
  10. }

Nous pouvons aussi modifier la fenêtre de sélection de fichier pour ne permettre que la sélection de fichiers exécutables et de dll.

  1. //
  2. // openFileDialog
  3. //
  4. openFileDialog = new OpenFileDialog();
  5. openFileDialog.Filter = "Executable files (.exe)|*.exe|Dynamic librairies (.dll)|*.dll";

Fichiers complets

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. namespace ClassExplorer
  9. {
  10. public partial class Form1 : Form
  11. {
  12. public Form1()
  13. {
  14. InitializeComponent();
  15. }
  16. private void fileToolStripMenuItem_Click(object sender, EventArgs e)
  17. {
  18. openFileDialog.ShowDialog();
  19. fillAndDisplayPathLabel();
  20. }
  21. private void fillAndDisplayPathLabel()
  22. {
  23. filePathLabel.Text = openFileDialog.FileName;
  24. filePathLabel.Visible = true;
  25. }
  26. }
  27. }
  1. using System.Windows.Forms;
  2. namespace ClassExplorer
  3. {
  4. partial class Form1
  5. {
  6. /// <summary>
  7. /// Required designer variable.
  8. /// </summary>
  9. private System.ComponentModel.IContainer components = null;
  10. /// <summary>
  11. /// Clean up any resources being used.
  12. /// </summary>
  13. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  14. protected override void Dispose(bool disposing)
  15. {
  16. if (disposing && (components != null))
  17. {
  18. components.Dispose();
  19. }
  20. base.Dispose(disposing);
  21. }
  22. #region Windows Form Designer generated code
  23. /// <summary>
  24. /// Required method for Designer support - do not modify
  25. /// the contents of this method with the code editor.
  26. /// </summary>
  27. private void InitializeComponent()
  28. {
  29. System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
  30. this.toolStrip1 = new System.Windows.Forms.ToolStrip();
  31. this.fileToolStripButton = new System.Windows.Forms.ToolStripDropDownButton();
  32. this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
  33. this.filePathLabel = new System.Windows.Forms.Label();
  34. this.toolStrip1.SuspendLayout();
  35. this.SuspendLayout();
  36. //
  37. // toolStrip1
  38. //
  39. this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
  40. this.fileToolStripButton});
  41. this.toolStrip1.Location = new System.Drawing.Point(0, 0);
  42. this.toolStrip1.Name = "toolStrip1";
  43. this.toolStrip1.Size = new System.Drawing.Size(292, 25);
  44. this.toolStrip1.TabIndex = 0;
  45. this.toolStrip1.Text = "toolStrip1";
  46. //
  47. // fileToolStripButton
  48. //
  49. this.fileToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
  50. this.fileToolStripButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
  51. this.fileToolStripMenuItem});
  52. this.fileToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("fileToolStripButton.Image")));
  53. this.fileToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
  54. this.fileToolStripButton.Name = "fileToolStripButton";
  55. this.fileToolStripButton.Size = new System.Drawing.Size(36, 22);
  56. this.fileToolStripButton.Text = "File";
  57. //
  58. // fileToolStripMenuItem
  59. //
  60. this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
  61. this.fileToolStripMenuItem.Size = new System.Drawing.Size(123, 22);
  62. this.fileToolStripMenuItem.Text = "Open...";
  63. this.fileToolStripMenuItem.Click += new System.EventHandler(this.fileToolStripMenuItem_Click);
  64. //
  65. // filePathLabel
  66. //
  67. this.filePathLabel.AutoSize = true;
  68. this.filePathLabel.Location = new System.Drawing.Point(12, 40);
  69. this.filePathLabel.Name = "filePathLabel";
  70. this.filePathLabel.Size = new System.Drawing.Size(0, 13);
  71. this.filePathLabel.TabIndex = 1;
  72. this.filePathLabel.Visible = false;
  73. //
  74. // Form1
  75. //
  76. this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  77. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  78. this.ClientSize = new System.Drawing.Size(292, 273);
  79. this.Controls.Add(this.filePathLabel);
  80. this.Controls.Add(this.toolStrip1);
  81. this.Name = "Form1";
  82. this.Text = "My Class Explorer";
  83. this.toolStrip1.ResumeLayout(false);
  84. this.toolStrip1.PerformLayout();
  85. this.ResumeLayout(false);
  86. this.PerformLayout();
  87. //
  88. // openFileDialog
  89. //
  90. openFileDialog = new OpenFileDialog();
  91. openFileDialog.Filter = "Executable files (.exe)|*.exe|Dynamic librairies (.dll)|*.dll";
  92. }
  93. #endregion
  94. private ToolStrip toolStrip1;
  95. private ToolStripDropDownButton fileToolStripButton;
  96. private ToolStripMenuItem fileToolStripMenuItem;
  97. private Label filePathLabel;
  98. private OpenFileDialog openFileDialog;
  99. }
  100. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. namespace ClassExplorer
  5. {
  6. static class Program
  7. {
  8. /// <summary>
  9. /// The main entry point for the application.
  10. /// </summary>
  11. [STAThread]
  12. static void Main()
  13. {
  14. Application.EnableVisualStyles();
  15. Application.SetCompatibleTextRenderingDefault(false);
  16. Application.Run(new Form1());
  17. }
  18. }
  19. }

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 26/09/2006, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/csharp-gui-menu.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.