Menus & Dialogs 📋
From Zero to Hero - Master Every Dialog!
Welcome to the Menus & Dialogs Master Class! 🎯
In this lesson, you'll learn EVERYTHING about Menus and Dialogs - from finding them in the toolbox to using them like a pro!
- ✅ Find and add MenuStrip from the Toolbox
- ✅ Create professional menus with shortcuts (Ctrl+S, Ctrl+O)
- ✅ Use OpenFileDialog - step by step
- ✅ Use SaveFileDialog - step by step
- ✅ Use PrintDialog - step by step
- ✅ Use ColorDialog - step by step
- ✅ Use FontDialog - step by step
- ✅ Use FolderBrowserDialog - step by step
- ✅ Create custom dialogs (About, Settings)
- ✅ Build a complete text editor with ALL dialogs!
Step 1: Adding a MenuStrip
🔍 How to Find It
- Open your form in the Designer (the visual editor)
- Look on the left side for the Toolbox tab
- If you don't see it, click View → Toolbox or press Ctrl + Alt + X
- In the Toolbox, find the "Menus & Toolbars" section
- You'll see MenuStrip - that's what you need!
📝 Creating Your First Menu
After dragging MenuStrip, you'll see "Type Here" boxes:
- Click the first "Type Here" and type &File
- Click the next "Type Here" and type &Edit
- Click the next "Type Here" and type &Help
- Now click below "File" and type &New
- Press Enter, type &Open
- Press Enter, type &Save
- Press Enter, type - (this creates a separator line)
- Press Enter, type E&xit
Step 2: Adding Keyboard Shortcuts
📝 How to Add Shortcuts
- Click on a menu item (like New under File)
- Look at the Properties window (usually bottom-right)
- Find the ShortcutKeys property
- Click the dropdown and select Ctrl + N
-
Do the same for other items:
- Open → Ctrl + O
- Save → Ctrl + S
- Exit → Alt + F4
💻 Complete Menu Code
When you're done, your menu structure looks like this:
// Menu structure in Designer
File
├── New (Ctrl+N)
├── Open (Ctrl+O)
├── Save (Ctrl+S)
├── ───────── (Separator)
└── Exit (Alt+F4)
Edit
├── Undo (Ctrl+Z)
├── Redo (Ctrl+Y)
├── ─────────
├── Cut (Ctrl+X)
├── Copy (Ctrl+C)
└── Paste (Ctrl+V)
Help
└── About (Alt+H, A)
📌 Every professional app has these menus!
Step 3: OpenFileDialog - From Zero to Hero
🔍 Where to Find OpenFileDialog
- Open the Toolbox (View → Toolbox or Ctrl+Alt+X)
- Find the "Dialogs" section (scroll down if needed)
- You'll see OpenFileDialog - it looks like a folder icon
- Important: Unlike buttons, you DON'T drag this to the form!
- Instead: Drag it to the component tray - the gray area below your form
- It will appear as a small icon below the form
💻 How to Use OpenFileDialog
Step 1: Double-click the "Open" menu item to create the click event
Step 2: Write this code:
// ===== OPEN FILE DIALOG - COMPLETE GUIDE =====
// This code goes in your Form.cs file
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
// 📌 STEP 1: Create a new OpenFileDialog
// This creates the dialog object in memory
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
// 📌 STEP 2: Configure the dialog
// These settings control what the user sees
// 👉 Title: What shows at the top of the dialog
openFileDialog.Title = "Select a file to open";
// 👉 Filter: What file types to show
// Format: "Description|*.extension|Description2|*.ext2"
openFileDialog.Filter = "Text Files (*.txt)|*.txt|" +
"All Files (*.*)|*.*";
// 👉 FilterIndex: Which filter is selected by default (1-based)
openFileDialog.FilterIndex = 1; // Shows "Text Files" first
// 👉 RestoreDirectory: Remember the last folder the user was in
openFileDialog.RestoreDirectory = true;
// 👉 Multiselect: Allow user to select multiple files
openFileDialog.Multiselect = false; // Only one file at a time
// 👉 InitialDirectory: Where to start looking
openFileDialog.InitialDirectory = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
// 📌 STEP 3: Show the dialog and check result
// ShowDialog() shows the window and waits for user action
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// 🎉 User clicked "Open" - now do something with the file
// 👉 Get the selected file path
string filePath = openFileDialog.FileName;
// 👉 Get just the file name (without the path)
string fileName = Path.GetFileName(filePath);
// 👉 Read the file content
try
{
string content = File.ReadAllText(filePath);
// 👉 Display the content in your textbox
txtContent.Text = content;
// 👉 Update status
lblStatus.Text = $"📂 Loaded: {fileName}";
lblStatus.ForeColor = Color.Green;
}
catch (Exception ex)
{
// 😱 Something went wrong - show error message
MessageBox.Show($"Error: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
// 🚫 User clicked "Cancel" - do nothing
lblStatus.Text = "Open cancelled";
lblStatus.ForeColor = Color.Blue;
}
}
// The 'using' block automatically disposes the dialog
}
Step 4: SaveFileDialog - From Zero to Hero
🔍 Where to Find SaveFileDialog
- Open the Toolbox (View → Toolbox or Ctrl+Alt+X)
- Find the "Dialogs" section
- You'll see SaveFileDialog - it looks like a floppy disk icon
- Again: Drag it to the component tray (gray area below form)
💻 How to Use SaveFileDialog
Method 1: Using the one you dragged to the tray
Method 2: Creating it in code (recommended for beginners)
// ===== SAVE FILE DIALOG - COMPLETE GUIDE =====
// This code goes in your Form.cs file
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// 📌 STEP 1: Check if there's anything to save
if (string.IsNullOrWhiteSpace(txtContent.Text))
{
MessageBox.Show("Nothing to save - the textbox is empty!",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// 📌 STEP 2: Create a new SaveFileDialog
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
// 📌 STEP 3: Configure the dialog
// 👉 Title: What shows at the top
saveFileDialog.Title = "Save your work";
// 👉 Filter: What file types to show
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|" +
"CSV Files (*.csv)|*.csv|" +
"All Files (*.*)|*.*";
// 👉 DefaultExt: What extension to add if user doesn't type one
saveFileDialog.DefaultExt = "txt";
// 👉 AddExtension: Automatically add extension
saveFileDialog.AddExtension = true;
// 👉 OverwritePrompt: Ask if user wants to overwrite existing file
saveFileDialog.OverwritePrompt = true;
// 👉 InitialDirectory: Where to start
saveFileDialog.InitialDirectory = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
// 👉 FileName: Default file name (optional)
saveFileDialog.FileName = "MyDocument";
// 📌 STEP 4: Show the dialog and check result
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// 🎉 User clicked "Save" - now save the file
// 👉 Get the chosen file path
string filePath = saveFileDialog.FileName;
// 👉 Save the content
try
{
File.WriteAllText(filePath, txtContent.Text);
// 👉 Update status
string fileName = Path.GetFileName(filePath);
lblStatus.Text = $"💾 Saved: {fileName}";
lblStatus.ForeColor = Color.Green;
// 👉 Show success message
MessageBox.Show("File saved successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
// 😱 Error saving
MessageBox.Show($"Error: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
// 🚫 User clicked "Cancel"
lblStatus.Text = "Save cancelled";
lblStatus.ForeColor = Color.Blue;
}
}
}
🖨️ How to Add Print Functionality (Step by Step)
STEP 1 Create a New Windows Forms Project
- Open Visual Studio
- Click "Create a new project"
- Search for "Windows Forms App" and select it
- Name your project "PrintDemo" and click Create
STEP 2 Add a DataGridView (To Show Your Data)
- Open the Toolbox (View → Toolbox or Ctrl + Alt + X)
- Find the "Data" section
- Drag DataGridView onto your form
- Resize it so it fills most of the form
- In the Properties window, set Dock = Fill
STEP 3 Add PrintDialog and PrintDocument
- Open the Toolbox again
- Find the "Dialogs" section
- Drag PrintDialog to the component tray (gray area below the form)
- Drag PrintDocument to the component tray as well
That's called the "component tray" - it's where non-visual components live.
STEP 4 Add a Print Button with Icon
- Open the Toolbox
- Find the "Common Controls" section
- Drag a Button to the top of your form
-
In the Properties window:
- Set Text = "&Print" (the & makes P the shortcut key)
- Set Image = Click the ... button → Select a printer icon
- Set ImageAlign = MiddleLeft
- Set TextAlign = MiddleRight
- Set Size = 120, 40
When users click it, they'll see the PrintDialog.
STEP 5 Add Sample Data to the DataGridView
Double-click the form (not the button) to create the Form_Load event.
// This code runs when the form loads
private void Form1_Load(object sender, EventArgs e)
{
// Create a DataTable (like a mini database)
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Columns.Add("Grade");
// Add rows
dt.Rows.Add("Alice", 20, "A");
dt.Rows.Add("Bob", 22, "B");
dt.Rows.Add("Charlie", 21, "A+");
// Show the data
dataGridView1.DataSource = dt;
}
✅ Now your DataGridView shows the student data!
STEP 6 Create the PrintPage Event
Double-click the PrintDocument in the component tray.
This creates the printDocument1_PrintPage event:
// This is where we DRAW what to print
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Font printFont = new Font("Arial", 12);
// Get data from the DataGridView
DataTable dt = (DataTable)dataGridView1.DataSource;
int y = 80;
// Print a title
e.Graphics.DrawString("Student Report",
new Font("Arial", 16, FontStyle.Bold),
Brushes.Black, 50, 30);
// Print headers
e.Graphics.DrawString("Name", printFont, Brushes.Black, 50, y);
e.Graphics.DrawString("Age", printFont, Brushes.Black, 150, y);
e.Graphics.DrawString("Grade", printFont, Brushes.Black, 250, y);
y += 30;
// Print each row
foreach (DataRow row in dt.Rows)
{
e.Graphics.DrawString(row[0].ToString(), printFont, Brushes.Black, 50, y);
e.Graphics.DrawString(row[1].ToString(), printFont, Brushes.Black, 150, y);
e.Graphics.DrawString(row[2].ToString(), printFont, Brushes.Black, 250, y);
y += 30;
}
e.HasMorePages = false;
}
📌 What's happening? We're drawing text on the page using e.Graphics.DrawString().
STEP 7 Connect the Print Button
Double-click the Print button to create the click event.
// This code runs when the Print button is clicked
private void btnPrint_Click(object sender, EventArgs e)
{
// 1️⃣ Connect PrintDialog to PrintDocument
printDialog1.Document = printDocument1;
// 2️⃣ Show the PrintDialog and check if user clicked OK
if (printDialog1.ShowDialog() == DialogResult.OK)
{
// 3️⃣ Start printing!
printDocument1.Print();
// 4️⃣ Show a message
MessageBox.Show("🖨️ Document sent to the printer!", "Print Success");
}
}
- The PrintDialog appears
- You choose your printer
- Click OK → Your table prints!
STEP 8 Complete Code - Copy and Paste
Here's the ENTIRE code for your form. Just copy and paste:
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace PrintDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// ========== FORM LOAD ==========
private void Form1_Load(object sender, EventArgs e)
{
// Create and fill a DataTable
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Columns.Add("Grade");
dt.Rows.Add("Alice", 20, "A");
dt.Rows.Add("Bob", 22, "B");
dt.Rows.Add("Charlie", 21, "A+");
dataGridView1.DataSource = dt;
}
// ========== PRINT BUTTON ==========
private void btnPrint_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.Print();
MessageBox.Show("🖨️ Printing started!", "Success");
}
}
// ========== PRINT DOCUMENT ==========
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Font printFont = new Font("Arial", 12);
DataTable dt = (DataTable)dataGridView1.DataSource;
int y = 80;
// Title
e.Graphics.DrawString("Student Report",
new Font("Arial", 16, FontStyle.Bold),
Brushes.Black, 50, 30);
// Headers
e.Graphics.DrawString("Name", printFont, Brushes.Black, 50, y);
e.Graphics.DrawString("Age", printFont, Brushes.Black, 150, y);
e.Graphics.DrawString("Grade", printFont, Brushes.Black, 250, y);
y += 30;
// Data rows
foreach (DataRow row in dt.Rows)
{
e.Graphics.DrawString(row[0].ToString(), printFont, Brushes.Black, 50, y);
e.Graphics.DrawString(row[1].ToString(), printFont, Brushes.Black, 150, y);
e.Graphics.DrawString(row[2].ToString(), printFont, Brushes.Black, 250, y);
y += 30;
}
e.HasMorePages = false;
}
}
}
🏆 What You Just Built!
- ✅ A Windows Forms app with a DataGridView
- ✅ Student data displayed in a table
- ✅ A Print button with a printer icon
- ✅ PrintDialog that lets users choose a printer
- ✅ PrintDocument that prints the table
- ✅ Formatted printing with title and headers
- ✅ All done using drag-and-drop + double-click!
- ✅ Zero manual code creation!
Step 6: ColorDialog - Pick Colors Like a Pro
🔍 Where to Find ColorDialog
- Open the Toolbox
- Find the "Dialogs" section
- You'll see ColorDialog - it's a color palette icon
- Drag it to the component tray
💻 How to Use ColorDialog
// ===== COLOR DIALOG - COMPLETE GUIDE =====
private void colorToolStripMenuItem_Click(object sender, EventArgs e)
{
// 📌 STEP 1: Create a ColorDialog
using (ColorDialog colorDialog = new ColorDialog())
{
// 📌 STEP 2: Configure it
colorDialog.FullOpen = true; // Show the full color palette
colorDialog.AnyColor = true; // Allow any color
// 👉 Set the starting color (current text color)
colorDialog.Color = txtContent.ForeColor;
// 📌 STEP 3: Show the dialog
if (colorDialog.ShowDialog() == DialogResult.OK)
{
// 🎉 User chose a color - apply it!
txtContent.ForeColor = colorDialog.Color;
lblStatus.Text = $"🎨 Color changed to {colorDialog.Color.Name}";
lblStatus.ForeColor = colorDialog.Color;
}
}
}
Step 7: FontDialog - Choose Fonts Like a Pro
🔍 Where to Find FontDialog
- Open the Toolbox
- Find the "Dialogs" section
- You'll see FontDialog - it's a font icon
- Drag it to the component tray
💻 How to Use FontDialog
// ===== FONT DIALOG - COMPLETE GUIDE =====
private void fontToolStripMenuItem_Click(object sender, EventArgs e)
{
// 📌 STEP 1: Create a FontDialog
using (FontDialog fontDialog = new FontDialog())
{
// 📌 STEP 2: Configure it
fontDialog.ShowColor = true; // Also show color picker
fontDialog.AllowVectorFonts = true;
fontDialog.ShowEffects = true;
// 👉 Set the starting font (current text font)
fontDialog.Font = txtContent.Font;
fontDialog.Color = txtContent.ForeColor;
// 📌 STEP 3: Show the dialog
if (fontDialog.ShowDialog() == DialogResult.OK)
{
// 🎉 User chose a font - apply it!
txtContent.Font = fontDialog.Font;
txtContent.ForeColor = fontDialog.Color;
lblStatus.Text = $"✏️ Font changed to {fontDialog.Font.Name} ({fontDialog.Font.Size}pt)";
lblStatus.ForeColor = Color.Green;
}
}
}
Step 8: FolderBrowserDialog - Choose Folders
🔍 Where to Find FolderBrowserDialog
- Open the Toolbox
- Find the "Dialogs" section
- You'll see FolderBrowserDialog - it's a folder icon
- Drag it to the component tray
💻 How to Use FolderBrowserDialog
// ===== FOLDER BROWSER DIALOG - COMPLETE GUIDE =====
private void folderToolStripMenuItem_Click(object sender, EventArgs e)
{
// 📌 STEP 1: Create a FolderBrowserDialog
using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
{
// 📌 STEP 2: Configure it
folderDialog.Description = "Select a folder to save your files";
folderDialog.ShowNewFolderButton = true;
folderDialog.RootFolder = Environment.SpecialFolder.MyComputer;
folderDialog.SelectedPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
// 📌 STEP 3: Show the dialog
if (folderDialog.ShowDialog() == DialogResult.OK)
{
// 🎉 User chose a folder
string selectedFolder = folderDialog.SelectedPath;
// 👉 Show the selected path
lblStatus.Text = $"📁 Selected folder: {selectedFolder}";
lblStatus.ForeColor = Color.Green;
// 👉 You can now use this folder to save files
MessageBox.Show($"You selected:\n{selectedFolder}",
"Folder Selected");
}
}
}
Step 9: Custom Dialogs - Your Own Pop-ups
📝 Creating a Custom Dialog
-
Add a new form
- Right-click project → Add → Windows Form
- Name it "AboutBox" or "SettingsForm"
-
Design it
- Add labels, picture boxes, buttons
- Set FormBorderStyle = FixedDialog
- Set MinimizeBox = false
- Set MaximizeBox = false
- Set StartPosition = CenterParent
-
Add a button with DialogResult
- Add an "OK" button
- Set its DialogResult property to OK
🎯 Using the Custom Dialog
// ===== ABOUT BOX - CUSTOM DIALOG =====
// AboutBox.cs - The dialog form
public partial class AboutBox : Form
{
public AboutBox()
{
InitializeComponent();
// Set the text in the labels
lblAppName.Text = "My Awesome App";
lblVersion.Text = "Version 1.0.0";
lblDescription.Text = "Built with C# and WinForms";
lblCopyright.Text = "© 2024 My Company";
}
}
// MainForm.cs - Show the dialog
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
// Create and show the About Box
using (AboutBox aboutBox = new AboutBox())
{
aboutBox.ShowDialog(); // Shows as modal dialog
}
}
✅ Users click About → See your custom dialog!
🎯 Master Exercise: Build a Complete Text Editor
What You'll Build:
-
MenuStrip with:
- 📂 File → New, Open, Save, Save As, Print, Exit
- ✏️ Edit → Cut, Copy, Paste, Select All
- 🎨 Format → Font, Color
- 📁 Tools → Choose Folder
- ❓ Help → About
-
TextBox:
- Dock = Fill
- Multiline = true
- ScrollBars = Both
- WordWrap = true
-
StatusStrip:
- Show file name
- Show word count
- Show character count
-
All Dialogs:
- OpenFileDialog
- SaveFileDialog
- PrintDialog
- PrintDocument
- ColorDialog
- FontDialog
- FolderBrowserDialog
- Custom About Dialog
// ===== COMPLETE TEXT EDITOR WITH ALL DIALOGS =====
// This is a fully functional text editor
// that uses EVERY dialog we learned
public partial class MainForm : Form
{
private string currentFileName = "";
private bool hasChanges = false;
public MainForm()
{
InitializeComponent();
UpdateStatus();
}
// ===== 📂 FILE MENU =====
// ✅ New Document
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CheckSaveChanges())
{
txtContent.Clear();
currentFileName = "";
hasChanges = false;
UpdateStatus();
}
}
// ✅ Open File (OpenFileDialog)
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CheckSaveChanges()) return;
using (OpenFileDialog openDlg = new OpenFileDialog())
{
openDlg.Title = "Open a text file";
openDlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openDlg.RestoreDirectory = true;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
txtContent.Text = File.ReadAllText(openDlg.FileName);
currentFileName = openDlg.FileName;
hasChanges = false;
UpdateStatus();
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
// ✅ Save File (SaveFileDialog)
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(currentFileName))
{
saveAsToolStripMenuItem_Click(sender, e);
return;
}
SaveFile(currentFileName);
}
// ✅ Save As (SaveFileDialog)
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveDlg = new SaveFileDialog())
{
saveDlg.Title = "Save your file";
saveDlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
saveDlg.DefaultExt = "txt";
saveDlg.OverwritePrompt = true;
if (saveDlg.ShowDialog() == DialogResult.OK)
{
SaveFile(saveDlg.FileName);
currentFileName = saveDlg.FileName;
UpdateStatus();
}
}
}
private void SaveFile(string fileName)
{
try
{
File.WriteAllText(fileName, txtContent.Text);
hasChanges = false;
UpdateStatus();
MessageBox.Show("File saved successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// ✅ Print (PrintDialog + PrintDocument)
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtContent.Text))
{
MessageBox.Show("Nothing to print!", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
try
{
printDocument1.Print();
lblStatus.Text = "🖨️ Document sent to printer";
lblStatus.ForeColor = Color.Green;
}
catch (Exception ex)
{
MessageBox.Show($"Print error: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// ✅ PrintDocument event
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
using (Font printFont = new Font("Arial", 12))
{
e.Graphics.DrawString(txtContent.Text, printFont,
Brushes.Black,
e.MarginBounds.Left, e.MarginBounds.Top);
}
e.HasMorePages = false;
}
// ✅ Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
// ===== ✏️ EDIT MENU =====
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (txtContent.SelectedText != "")
{
Clipboard.SetText(txtContent.SelectedText);
txtContent.Cut();
hasChanges = true;
UpdateStatus();
}
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (txtContent.SelectedText != "")
{
Clipboard.SetText(txtContent.SelectedText);
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsText())
{
txtContent.Paste();
hasChanges = true;
UpdateStatus();
}
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
txtContent.SelectAll();
}
// ===== 🎨 FORMAT MENU =====
// ✅ Font Dialog
private void fontToolStripMenuItem_Click(object sender, EventArgs e)
{
using (FontDialog fontDlg = new FontDialog())
{
fontDlg.Font = txtContent.Font;
fontDlg.Color = txtContent.ForeColor;
fontDlg.ShowColor = true;
if (fontDlg.ShowDialog() == DialogResult.OK)
{
txtContent.Font = fontDlg.Font;
txtContent.ForeColor = fontDlg.Color;
UpdateStatus();
}
}
}
// ✅ Color Dialog
private void colorToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDlg = new ColorDialog())
{
colorDlg.Color = txtContent.ForeColor;
colorDlg.FullOpen = true;
if (colorDlg.ShowDialog() == DialogResult.OK)
{
txtContent.ForeColor = colorDlg.Color;
UpdateStatus();
}
}
}
// ===== 📁 TOOLS MENU =====
// ✅ FolderBrowserDialog
private void folderToolStripMenuItem_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
{
folderDlg.Description = "Select a folder";
folderDlg.ShowNewFolderButton = true;
if (folderDlg.ShowDialog() == DialogResult.OK)
{
lblStatus.Text = $"📁 Selected: {folderDlg.SelectedPath}";
lblStatus.ForeColor = Color.Green;
}
}
}
// ===== ❓ HELP MENU =====
// ✅ Custom About Dialog
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
using (AboutBox aboutBox = new AboutBox())
{
aboutBox.ShowDialog();
}
}
// ===== 📊 STATUS BAR =====
private void txtContent_TextChanged(object sender, EventArgs e)
{
hasChanges = true;
UpdateStatus();
}
private void UpdateStatus()
{
// Word count
int wordCount = txtContent.Text.Split(
new char[] { ' ', '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries).Length;
// File name
string fileName = string.IsNullOrWhiteSpace(currentFileName) ?
"Untitled" : Path.GetFileName(currentFileName);
// Modified marker
string modified = hasChanges ? " *" : "";
// Update status bar
lblStatus.Text = $"📄 {fileName}{modified} | 📊 Words: {wordCount} | 📝 Chars: {txtContent.Text.Length}";
}
// ===== 🚪 FORM CLOSING =====
private bool CheckSaveChanges()
{
if (!hasChanges) return true;
DialogResult result = MessageBox.Show(
"Do you want to save changes?",
"Unsaved Changes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning
);
if (result == DialogResult.Yes)
{
saveToolStripMenuItem_Click(this, EventArgs.Empty);
return !hasChanges;
}
else if (result == DialogResult.No)
{
return true;
}
return false;
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!CheckSaveChanges())
{
e.Cancel = true;
}
}
}
// ===== ABOUT BOX (Custom Dialog) =====
public partial class AboutBox : Form
{
public AboutBox()
{
InitializeComponent();
// Set the text in the labels
lblAppName.Text = "My Awesome Text Editor";
lblVersion.Text = "Version 1.0.0";
lblDescription.Text = "Built with C# and WinForms\nusing all dialogs and menus";
lblCopyright.Text = "© 2024 C# Mastery Hub";
}
}
🎉 Mastery Summary - What You Learned Today!
Menus
File, Edit, HelpOpenFileDialog
Open filesSaveFileDialog
Save filesPrintDialog
Print documentsColorDialog
Choose colorsFontDialog
Choose fontsFolderBrowserDialog
Choose foldersCustom Dialogs
About, Settings🎯 You're now a MASTER of Menus and Dialogs in WinForms!