Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

C#

Windows Desktop Features - C# Samples

Comprehensive C# desktop features examples for Windows platform including file dialogs, message boxes, and system tray integration

Samples

Entries inside this sample collection

CodecsharpSimple

File Dialog Operations

Open and save file dialogs with custom filters and options

Difficulty

3/10

Estimated time

20 min

Tags

csharp, dialog, file, windows, desktop

Prerequisites

Windows Forms basics, File system operations

csharp
using System;
using System.IO;
using System.Windows.Forms;
using System.Text;

// Note: These examples require references to System.Windows.Forms
// Add reference: System.Windows.Forms.dll
// Or use Windows Forms or WPF applications for full functionality

class FileDialogExamples
{
    // 1. Simple Open File Dialog
    public static string ShowOpenFileDialog()
    {
        Console.WriteLine("=== Open File Dialog Example ===");

        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            // Configure dialog properties
            openFileDialog.Title = "Select a file to open";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            openFileDialog.Multiselect = false;

            // Show dialog and process result
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFile = openFileDialog.FileName;
                Console.WriteLine($"Selected file: {selectedFile}");
                Console.WriteLine($"File size: {new FileInfo(selectedFile).Length:N0} bytes");
                return selectedFile;
            }
            else
            {
                Console.WriteLine("No file selected");
                return null;
            }
        }
    }

    // 2. Save File Dialog
    public static string ShowSaveFileDialog()
    {
        Console.WriteLine("=== Save File Dialog Example ===");

        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        {
            // Configure dialog properties
            saveFileDialog.Title = "Save your file";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.AddExtension = true;
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.FileName = $"document_{DateTime.Now:yyyyMMdd_HHmmss}.txt";

            // Show dialog and process result
            DialogResult result = saveFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string savePath = saveFileDialog.FileName;
                Console.WriteLine($"File will be saved to: {savePath}");

                // Create some sample content
                string content = $"Sample document created on {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n" +
                               $"This is a test file created by the Save File Dialog example.\n" +
                               $"You can modify this content as needed.";

                try
                {
                    File.WriteAllText(savePath, content);
                    Console.WriteLine("File saved successfully!");
                    return savePath;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error saving file: {ex.Message}");
                    return null;
                }
            }
            else
            {
                Console.WriteLine("Save operation cancelled");
                return null;
            }
        }
    }

    // 3. Multi-select Open Dialog
    public static string[] ShowMultiSelectDialog()
    {
        Console.WriteLine("=== Multi-select File Dialog Example ===");

        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            // Configure dialog for multiple file selection
            openFileDialog.Title = "Select multiple files";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|Image Files (*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = true;

            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string[] selectedFiles = openFileDialog.FileNames;
                Console.WriteLine($"Selected {selectedFiles.Length} files:");

                long totalSize = 0;
                foreach (string file in selectedFiles)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    totalSize += fileInfo.Length;
                    Console.WriteLine($"  - {fileInfo.Name} ({FormatFileSize(fileInfo.Length)})");
                }

                Console.WriteLine($"Total size: {FormatFileSize(totalSize)}");
                return selectedFiles;
            }
            else
            {
                Console.WriteLine("No files selected");
                return new string[0];
            }
        }
    }

    // 4. Folder Browser Dialog
    public static string ShowFolderBrowserDialog()
    {
        Console.WriteLine("=== Folder Browser Dialog Example ===");

        using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
        {
            // Configure dialog properties
            folderBrowserDialog.Description = "Select a folder for file operations";
            folderBrowserDialog.ShowNewFolderButton = true;
            folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;

            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFolder = folderBrowserDialog.SelectedPath;
                Console.WriteLine($"Selected folder: {selectedFolder}");

                // Get folder information
                DirectoryInfo dirInfo = new DirectoryInfo(selectedFolder);
                var files = dirInfo.GetFiles();
                var directories = dirInfo.GetDirectories();

                Console.WriteLine($"Folder contents:");
                Console.WriteLine($"  Files: {files.Length}");
                Console.WriteLine($"  Subdirectories: {directories.Length}");

                if (files.Length > 0)
                {
                    Console.WriteLine("Sample files:");
                    foreach (var file in files.Take(5))
                    {
                        Console.WriteLine($"  - {file.Name} ({FormatFileSize(file.Length)})");
                    }
                }

                return selectedFolder;
            }
            else
            {
                Console.WriteLine("No folder selected");
                return null;
            }
        }
    }

    // 5. Custom File Dialog with Preview
    public static string ShowCustomFileDialog()
    {
        Console.WriteLine("=== Custom File Dialog with Preview ===");

        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            // Configure dialog
            openFileDialog.Title = "Select a text file for preview";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Filter = "Text Files (*.txt;*.log;*.csv)|*.txt;*.log;*.csv|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            // Custom event handler for file selection change
            openFileDialog.FileOk += (sender, e) =>
            {
                string selectedFile = openFileDialog.FileName;

                if (File.Exists(selectedFile) && IsTextFile(selectedFile))
                {
                    try
                    {
                        // Read first few lines for preview
                        string[] lines = File.ReadAllLines(selectedFile);
                        Console.WriteLine($"\n--- Preview of {Path.GetFileName(selectedFile)} ---");

                        for (int i = 0; i < Math.Min(5, lines.Length); i++)
                        {
                            string line = lines[i].Length > 50 ? lines[i].Substring(0, 50) + "..." : lines[i];
                            Console.WriteLine($"Line {i + 1}: {line}");
                        }

                        if (lines.Length > 5)
                        {
                            Console.WriteLine($"... and {lines.Length - 5} more lines");
                        }

                        Console.WriteLine($"--- End Preview ---\n");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Could not preview file: {ex.Message}");
                    }
                }
                else
                {
                    Console.WriteLine("Selected file is not a text file or cannot be read for preview");
                }
            };

            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFile = openFileDialog.FileName;
                Console.WriteLine($"Final selection: {selectedFile}");
                return selectedFile;
            }
            else
            {
                Console.WriteLine("No file selected");
                return null;
            }
        }
    }

    // 6. File Dialog with Custom Filters
    public static void ShowDialogWithCustomFilters()
    {
        Console.WriteLine("=== File Dialog with Custom Filters ===");

        // Define custom filters
        var filters = new[]
        {
            new { Name = "Documents", Extensions = "*.txt;*.doc;*.docx;*.pdf" },
            new { Name = "Images", Extensions = "*.jpg;*.jpeg;*.png;*.gif;*.bmp" },
            new { Name = "Code Files", Extensions = "*.cs;*.js;*.html;*.css;*.xml" },
            new { Name = "Data Files", Extensions = "*.csv;*.json;*.xml;*.yaml" },
            new { Name = "All Files", Extensions = "*.*" }
        };

        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            // Build custom filter string
            StringBuilder filterBuilder = new StringBuilder();
            foreach (var filter in filters)
            {
                filterBuilder.Append($"{filter.Name}|{filter.Extensions}|");
            }

            // Remove trailing pipe
            string filterString = filterBuilder.ToString().TrimEnd('|');
            openFileDialog.Filter = filterString;
            openFileDialog.FilterIndex = 1;
            openFileDialog.Title = "Select a file with custom filters";

            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFile = openFileDialog.FileName;
                string extension = Path.GetExtension(selectedFile).ToLower();

                Console.WriteLine($"Selected file: {selectedFile}");
                Console.WriteLine($"File extension: {extension}");

                // Determine which filter was used
                int selectedFilterIndex = openFileDialog.FilterIndex - 1;
                if (selectedFilterIndex >= 0 && selectedFilterIndex < filters.Length)
                {
                    var selectedFilter = filters[selectedFilterIndex];
                    Console.WriteLine($"Filter used: {selectedFilter.Name}");
                }
            }
            else
            {
                Console.WriteLine("No file selected");
            }
        }
    }

    // 7. Batch File Processing Dialog
    public static void BatchFileProcessing()
    {
        Console.WriteLine("=== Batch File Processing Dialog ===");

        // Step 1: Select source folder
        string sourceFolder = null;
        using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
        {
            folderDialog.Description = "Select source folder containing files to process";
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                sourceFolder = folderDialog.SelectedPath;
                Console.WriteLine($"Source folder: {sourceFolder}");
            }
            else
            {
                Console.WriteLine("No source folder selected");
                return;
            }
        }

        // Step 2: Select destination folder
        string destinationFolder = null;
        using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
        {
            folderDialog.Description = "Select destination folder for processed files";
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                destinationFolder = folderDialog.SelectedPath;
                Console.WriteLine($"Destination folder: {destinationFolder}");
            }
            else
            {
                Console.WriteLine("No destination folder selected");
                return;
            }
        }

        // Step 3: Process files
        if (!string.IsNullOrEmpty(sourceFolder) && !string.IsNullOrEmpty(destinationFolder))
        {
            try
            {
                var sourceFiles = Directory.GetFiles(sourceFolder, "*.txt");
                Console.WriteLine($"Found {sourceFiles.Length} text files to process");

                int processedCount = 0;
                foreach (string sourceFile in sourceFiles)
                {
                    string fileName = Path.GetFileName(sourceFile);
                    string destFile = Path.Combine(destinationFolder, $"processed_{fileName}");

                    // Simple processing: add timestamp to the beginning
                    string originalContent = File.ReadAllText(sourceFile);
                    string processedContent = $"Processed on {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n\n{originalContent}";

                    File.WriteAllText(destFile, processedContent);
                    processedCount++;

                    Console.WriteLine($"Processed: {fileName}");
                }

                Console.WriteLine($"\nBatch processing completed! {processedCount} files processed.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during batch processing: {ex.Message}");
            }
        }
    }

    // Helper methods
    private static bool IsTextFile(string filePath)
    {
        string extension = Path.GetExtension(filePath).ToLower();
        string[] textExtensions = { ".txt", ".log", ".csv", ".json", ".xml", ".html", ".css", ".js", ".cs", ".md" };
        return textExtensions.Contains(extension);
    }

    private static string FormatFileSize(long bytes)
    {
        string[] sizes = { "B", "KB", "MB", "GB", "TB" };
        int order = 0;
        double size = bytes;

        while (size >= 1024 && order < sizes.Length - 1)
        {
            order++;
            size /= 1024;
        }

        return $"{size:F2} {sizes[order]}";
    }

    // Main method for demonstration
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("=== C# File Dialog Examples ===\n");
        Console.WriteLine("Note: These examples require a Windows Forms application context.");
        Console.WriteLine("Some examples may not work in console mode.\n");

        try
        {
            // Enable visual styles for better dialog appearance
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Run examples
            ShowOpenFileDialog();
            Console.WriteLine();

            ShowSaveFileDialog();
            Console.WriteLine();

            ShowMultiSelectDialog();
            Console.WriteLine();

            ShowFolderBrowserDialog();
            Console.WriteLine();

            ShowCustomFileDialog();
            Console.WriteLine();

            ShowDialogWithCustomFilters();
            Console.WriteLine();

            BatchFileProcessing();

            Console.WriteLine("\nAll file dialog examples completed!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error running examples: {ex.Message}");
        }
    }
}
CodecsharpSimple

Message Box Operations

Various types of message boxes with different buttons, icons, and custom behaviors

Difficulty

3/10

Estimated time

15 min

Tags

csharp, messagebox, dialog, windows, desktop

Prerequisites

Windows Forms basics, Dialog handling

csharp
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;

// Note: These examples require references to System.Windows.Forms
// Add reference: System.Windows.Forms.dll

class MessageBoxExamples
{
    // 1. Simple Information Message Box
    public static void ShowInformationMessage()
    {
        Console.WriteLine("=== Information Message Box ===");

        string message = "This is an information message.\n\n" +
                        "Information messages are used to provide important " +
                        "information to the user that they need to be aware of.";

        string title = "Information";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.OK,
            MessageBoxIcon.Information,
            MessageBoxDefaultButton.Button1
        );

        Console.WriteLine($"Message box result: {result}");
    }

    // 2. Warning Message Box
    public static void ShowWarningMessage()
    {
        Console.WriteLine("=== Warning Message Box ===");

        string message = "Warning: You are about to perform an action that cannot be undone.\n\n" +
                        "Please make sure you want to continue before proceeding.";

        string title = "Warning";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.OKCancel,
            MessageBoxIcon.Warning,
            MessageBoxDefaultButton.Button2
        );

        Console.WriteLine($"Warning message result: {result}");

        if (result == DialogResult.OK)
        {
            Console.WriteLine("User chose to proceed with the action");
        }
        else
        {
            Console.WriteLine("User cancelled the action");
        }
    }

    // 3. Error Message Box
    public static void ShowErrorMessage()
    {
        Console.WriteLine("=== Error Message Box ===");

        string message = "An error has occurred while processing your request.\n\n" +
                        "Error details: The specified file could not be found.\n" +
                        "Please check the file path and try again.";

        string title = "Error";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.OK,
            MessageBoxIcon.Error,
            MessageBoxDefaultButton.Button1
        );

        Console.WriteLine($"Error message result: {result}");
    }

    // 4. Question Message Box with Yes/No
    public static void ShowQuestionMessage()
    {
        Console.WriteLine("=== Question Message Box ===");

        string message = "Do you want to save the changes before closing?\n\n" +
                        "Any unsaved changes will be lost if you don't save.";

        string title = "Save Changes";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Question,
            MessageBoxDefaultButton.Button1
        );

        Console.WriteLine($"Question result: {result}");

        switch (result)
        {
            case DialogResult.Yes:
                Console.WriteLine("User chose to save changes");
                break;
            case DialogResult.No:
                Console.WriteLine("User chose not to save changes");
                break;
            default:
                Console.WriteLine("User closed the dialog without choosing");
                break;
        }
    }

    // 5. Yes/No/Cancel Message Box
    public static void ShowYesNoCancelMessage()
    {
        Console.WriteLine("=== Yes/No/Cancel Message Box ===");

        string message = "The document has been modified.\n\n" +
                        "Do you want to save the changes?";

        string title = "Unsaved Changes";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.YesNoCancel,
            MessageBoxIcon.Question,
            MessageBoxDefaultButton.Button1
        );

        Console.WriteLine($"Yes/No/Cancel result: {result}");

        switch (result)
        {
            case DialogResult.Yes:
                Console.WriteLine("User chose to save the document");
                break;
            case DialogResult.No:
                Console.WriteLine("User chose not to save the document");
                break;
            case DialogResult.Cancel:
                Console.WriteLine("User cancelled the operation");
                break;
            default:
                Console.WriteLine("User closed the dialog");
                break;
        }
    }

    // 6. Retry/Cancel Message Box
    public static void ShowRetryCancelMessage()
    {
        Console.WriteLine("=== Retry/Cancel Message Box ===");

        string message = "Connection to the server failed.\n\n" +
                        "Would you like to try again?";

        string title = "Connection Failed";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.RetryCancel,
            MessageBoxIcon.Exclamation,
            MessageBoxDefaultButton.Button1
        );

        Console.WriteLine($"Retry/Cancel result: {result}");

        int attempts = 1;
        while (result == DialogResult.Retry && attempts < 3)
        {
            Console.WriteLine($"Attempt {attempts + 1}: Retrying connection...");
            attempts++;

            // Simulate connection attempt
            System.Threading.Thread.Sleep(1000);

            // Show retry dialog again
            result = MessageBox.Show(
                $"Connection attempt {attempts} failed.\n\nWould you like to try again?\n(Attempt {attempts} of 3)",
                "Connection Failed",
                MessageBoxButtons.RetryCancel,
                MessageBoxIcon.Exclamation
            );
        }

        if (result == DialogResult.Cancel || attempts >= 3)
        {
            Console.WriteLine("User cancelled or max attempts reached");
        }
    }

    // 7. Abort/Retry/Ignore Message Box
    public static void ShowAbortRetryIgnoreMessage()
    {
        Console.WriteLine("=== Abort/Retry/Ignore Message Box ===");

        string message = "A file access error occurred during processing.\n\n" +
                        "What would you like to do?";

        string title = "File Access Error";
        DialogResult result = MessageBox.Show(
            message,
            title,
            MessageBoxButtons.AbortRetryIgnore,
            MessageBoxIcon.Exclamation,
            MessageBoxDefaultButton.Button2
        );

        Console.WriteLine($"Abort/Retry/Ignore result: {result}");

        switch (result)
        {
            case DialogResult.Abort:
                Console.WriteLine("User chose to abort the entire operation");
                break;
            case DialogResult.Retry:
                Console.WriteLine("User chose to retry the file access");
                break;
            case DialogResult.Ignore:
                Console.WriteLine("User chose to ignore this error and continue");
                break;
            default:
                Console.WriteLine("User closed the dialog");
                break;
        }
    }

    // 8. Custom Message Box with Custom Buttons
    public static DialogResult ShowCustomMessageBox(string title, string message, params string[] buttons)
    {
        Console.WriteLine("=== Custom Message Box ===");

        // Create a custom dialog form
        Form customDialog = new Form();
        customDialog.Text = title;
        customDialog.Size = new Size(400, 200);
        customDialog.StartPosition = FormStartPosition.CenterScreen;
        customDialog.FormBorderStyle = FormBorderStyle.FixedDialog;
        customDialog.MaximizeBox = false;
        customDialog.MinimizeBox = false;

        // Add message label
        Label messageLabel = new Label();
        messageLabel.Text = message;
        messageLabel.Location = new Point(20, 20);
        messageLabel.Size = new Size(360, 80);
        messageLabel.TextAlign = ContentAlignment.MiddleCenter;
        customDialog.Controls.Add(messageLabel);

        // Add buttons
        int buttonWidth = 80;
        int buttonHeight = 30;
        int spacing = 10;
        int totalButtonWidth = buttons.Length * buttonWidth + (buttons.Length - 1) * spacing;
        int startX = (400 - totalButtonWidth) / 2;
        int startY = 120;

        DialogResult dialogResult = DialogResult.None;

        for (int i = 0; i < buttons.Length; i++)
        {
            Button button = new Button();
            button.Text = buttons[i];
            button.Location = new Point(startX + i * (buttonWidth + spacing), startY);
            button.Size = new Size(buttonWidth, buttonHeight);

            int buttonIndex = i;
            button.Click += (sender, e) =>
            {
                dialogResult = (DialogResult)(buttonIndex + 1); // Custom DialogResult values
                customDialog.DialogResult = dialogResult;
                customDialog.Close();
            };

            customDialog.Controls.Add(button);
        }

        // Show dialog
        customDialog.ShowDialog();

        Console.WriteLine($"Custom message box result: {dialogResult}");
        return dialogResult;
    }

    // 9. Message Box with Timeout (custom implementation)
    public static void ShowTimeoutMessageBox()
    {
        Console.WriteLine("=== Timeout Message Box ===");

        // Create a form that auto-closes after timeout
        Form timeoutForm = new Form();
        timeoutForm.Text = "Auto-close Message";
        timeoutForm.Size = new Size(350, 150);
        timeoutForm.StartPosition = FormStartPosition.CenterScreen;
        timeoutForm.FormBorderStyle = FormBorderStyle.FixedDialog;
        timeoutForm.MaximizeBox = false;
        timeoutForm.MinimizeBox = false;
        timeoutForm.TopMost = true;

        // Add message label
        Label messageLabel = new Label();
        messageLabel.Text = "This message will automatically close in 5 seconds.\n\n" +
                           "You can also click OK to close it immediately.";
        messageLabel.Location = new Point(20, 20);
        messageLabel.Size = new Size(310, 60);
        timeoutForm.Controls.Add(messageLabel);

        // Add OK button
        Button okButton = new Button();
        okButton.Text = "OK";
        okButton.Location = new Point(140, 90);
        okButton.Click += (sender, e) =>
        {
            timeoutForm.DialogResult = DialogResult.OK;
            timeoutForm.Close();
        };
        timeoutForm.Controls.Add(okButton);

        // Set up timer for auto-close
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Interval = 5000; // 5 seconds
        timer.Tick += (sender, e) =>
        {
            timer.Stop();
            timeoutForm.DialogResult = DialogResult.Cancel;
            timeoutForm.Close();
        };
        timer.Start();

        DialogResult result = timeoutForm.ShowDialog();
        timer.Stop();

        Console.WriteLine($"Timeout message box result: {result}");
    }

    // 10. Input Message Box (custom implementation)
    public static string ShowInputMessageBox(string title, string prompt, string defaultValue = "")
    {
        Console.WriteLine("=== Input Message Box ===");

        // Create a custom input dialog
        Form inputForm = new Form();
        inputForm.Text = title;
        inputForm.Size = new Size(400, 200);
        inputForm.StartPosition = FormStartPosition.CenterScreen;
        inputForm.FormBorderStyle = FormBorderStyle.FixedDialog;
        inputForm.MaximizeBox = false;
        inputForm.MinimizeBox = false;

        // Add prompt label
        Label promptLabel = new Label();
        promptLabel.Text = prompt;
        promptLabel.Location = new Point(20, 20);
        promptLabel.Size = new Size(360, 40);
        inputForm.Controls.Add(promptLabel);

        // Add text box
        TextBox inputTextBox = new TextBox();
        inputTextBox.Text = defaultValue;
        inputTextBox.Location = new Point(20, 70);
        inputTextBox.Size = new Size(360, 25);
        inputForm.Controls.Add(inputTextBox);

        // Add OK button
        Button okButton = new Button();
        okButton.Text = "OK";
        okButton.Location = new Point(210, 110);
        okButton.Size = new Size(80, 30);
        okButton.Click += (sender, e) =>
        {
            inputForm.DialogResult = DialogResult.OK;
            inputForm.Close();
        };
        inputForm.Controls.Add(okButton);

        // Add Cancel button
        Button cancelButton = new Button();
        cancelButton.Text = "Cancel";
        cancelButton.Location = new Point(300, 110);
        cancelButton.Size = new Size(80, 30);
        cancelButton.Click += (sender, e) =>
        {
            inputForm.DialogResult = DialogResult.Cancel;
            inputForm.Close();
        };
        inputForm.Controls.Add(cancelButton);

        // Set default button and accept button
        inputForm.AcceptButton = okButton;
        inputForm.CancelButton = cancelButton;

        DialogResult result = inputForm.ShowDialog();

        string inputValue = inputTextBox.Text;
        Console.WriteLine($"Input dialog result: {result}, Input value: '{inputValue}'");

        return result == DialogResult.OK ? inputValue : null;
    }

    // Demonstration method
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("=== C# Message Box Examples ===\n");
        Console.WriteLine("Note: These examples require a Windows Forms application context.");
        Console.WriteLine("Some examples may not work in console mode.\n");

        try
        {
            // Enable visual styles
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Run different message box examples
            Console.WriteLine("1. Information Message Box:");
            ShowInformationMessage();
            Console.WriteLine();

            Console.WriteLine("2. Warning Message Box:");
            ShowWarningMessage();
            Console.WriteLine();

            Console.WriteLine("3. Error Message Box:");
            ShowErrorMessage();
            Console.WriteLine();

            Console.WriteLine("4. Question Message Box:");
            ShowQuestionMessage();
            Console.WriteLine();

            Console.WriteLine("5. Yes/No/Cancel Message Box:");
            ShowYesNoCancelMessage();
            Console.WriteLine();

            Console.WriteLine("6. Retry/Cancel Message Box:");
            ShowRetryCancelMessage();
            Console.WriteLine();

            Console.WriteLine("7. Abort/Retry/Ignore Message Box:");
            ShowAbortRetryIgnoreMessage();
            Console.WriteLine();

            Console.WriteLine("8. Custom Message Box:");
            DialogResult customResult = ShowCustomMessageBox(
                "Custom Options",
                "Choose one of the following options:",
                "Option 1", "Option 2", "Option 3"
            );
            Console.WriteLine();

            Console.WriteLine("9. Timeout Message Box:");
            ShowTimeoutMessageBox();
            Console.WriteLine();

            Console.WriteLine("10. Input Message Box:");
            string userInput = ShowInputMessageBox(
                "User Input",
                "Please enter your name:",
                "John Doe"
            );
            if (!string.IsNullOrEmpty(userInput))
            {
                Console.WriteLine($"User entered: {userInput}");
            }
            Console.WriteLine();

            Console.WriteLine("All message box examples completed!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error running examples: {ex.Message}");
        }
    }
}
CodecsharpIntermediate

System Tray Integration

Create system tray applications with notifications, context menus, and background operations

Difficulty

5/10

Estimated time

25 min

Tags

csharp, system tray, notification, background, windows

Prerequisites

Windows Forms, Threading basics, Async programming

csharp
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Diagnostics;

// Note: These examples require references to System.Windows.Forms and System.Drawing

class SystemTrayExamples : ApplicationContext
{
    private NotifyIcon _notifyIcon;
    private ContextMenuStrip _contextMenu;
    private int _notificationCount = 0;

    // Main application context
    public SystemTrayExamples()
    {
        Console.WriteLine("=== System Tray Application Started ===");

        // Create and configure the system tray icon
        CreateNotifyIcon();

        // Create context menu
        CreateContextMenu();

        // Show initial notification
        ShowNotification("System Tray App", "Application started successfully!");

        // Start background task for periodic notifications
        StartBackgroundTask();
    }

    // 1. Create and configure NotifyIcon
    private void CreateNotifyIcon()
    {
        _notifyIcon = new NotifyIcon
        {
            Icon = SystemIcons.Application, // Use default application icon
            Text = "System Tray Example Application",
            Visible = true
        };

        // Handle double-click to show main form
        _notifyIcon.DoubleClick += (sender, e) =>
        {
            Console.WriteLine("System tray icon double-clicked");
            ShowMainForm();
        };

        // Handle mouse click events
        _notifyIcon.MouseClick += (sender, e) =>
        {
            if (e.Button == MouseButtons.Right)
            {
                Console.WriteLine("System tray icon right-clicked");
            }
        };
    }

    // 2. Create context menu
    private void CreateContextMenu()
    {
        _contextMenu = new ContextMenuStrip();

        // Show main form
        ToolStripItem showItem = _contextMenu.Items.Add("Show Main Form");
        showItem.Click += (sender, e) => ShowMainForm();

        // Separator
        _contextMenu.Items.Add(new ToolStripSeparator());

        // Actions menu
        ToolStripMenuItem actionsItem = (ToolStripMenuItem)_contextMenu.Items.Add("Actions");

        ToolStripItem notifyItem = actionsItem.DropDownItems.Add("Send Test Notification");
        notifyItem.Click += (sender, e) => ShowNotification("Test", "This is a test notification!");

        ToolStripItem logItem = actionsItem.DropDownItems.Add("Log Current Time");
        logItem.Click += (sender, e) =>
        {
            string message = $"Current time logged: {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
            Console.WriteLine(message);
            ShowNotification("Log", message);
        };

        ToolStripItem infoItem = actionsItem.DropDownItems.Add("Show System Info");
        infoItem.Click += (sender, e) => ShowSystemInfo();

        // Separator
        _contextMenu.Items.Add(new ToolStripSeparator());

        // Settings menu
        ToolStripMenuItem settingsItem = (ToolStripMenuItem)_contextMenu.Items.Add("Settings");

        ToolStripMenuItem soundItem = new ToolStripMenuItem("Enable Sound");
        soundItem.Checked = true;
        soundItem.Click += (sender, e) =>
        {
            soundItem.Checked = !soundItem.Checked;
            Console.WriteLine($"Sound enabled: {soundItem.Checked}");
        };
        settingsItem.DropDownItems.Add(soundItem);

        ToolStripMenuItem balloonItem = new ToolStripMenuItem("Show Balloon Tips");
        balloonItem.Checked = true;
        balloonItem.Click += (sender, e) =>
        {
            balloonItem.Checked = !balloonItem.Checked;
            Console.WriteLine($"Balloon tips enabled: {balloonItem.Checked}");
        };
        settingsItem.DropDownItems.Add(balloonItem);

        // Separator
        _contextMenu.Items.Add(new ToolStripSeparator());

        // About
        ToolStripItem aboutItem = _contextMenu.Items.Add("About");
        aboutItem.Click += (sender, e) => ShowAboutDialog();

        // Exit
        ToolStripItem exitItem = _contextMenu.Items.Add("Exit");
        exitItem.Click += (sender, e) => ExitApplication();

        // Assign context menu to notify icon
        _notifyIcon.ContextMenuStrip = _contextMenu;
    }

    // 3. Show main form (optional)
    private void ShowMainForm()
    {
        Form mainForm = new Form
        {
            Text = "System Tray Example",
            Size = new Size(400, 300),
            StartPosition = FormStartPosition.CenterScreen
        };

        // Add some content to the form
        Label label = new Label
        {
            Text = "This is the main form of the system tray application.\n\n" +
                   "You can minimize this form to the system tray using the " +
                   "button below, or close it to keep the application running " +
                   "in the background.",
            Location = new Point(20, 20),
            Size = new Size(360, 100),
            TextAlign = ContentAlignment.MiddleCenter
        };
        mainForm.Controls.Add(label);

        // Add minimize to tray button
        Button minimizeButton = new Button
        {
            Text = "Minimize to Tray",
            Location = new Point(140, 140),
            Size = new Size(120, 30)
        };
        minimizeButton.Click += (sender, e) =>
        {
            mainForm.Hide();
            ShowNotification("Minimized", "Application minimized to system tray");
        };
        mainForm.Controls.Add(minimizeButton);

        // Add status label
        Label statusLabel = new Label
        {
            Text = $"Application started: {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
            Location = new Point(20, 200),
            Size = new Size(360, 30)
        };
        mainForm.Controls.Add(statusLabel);

        mainForm.FormClosing += (sender, e) =>
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                mainForm.Hide();
                ShowNotification("Hidden", "Application running in background");
            }
        };

        mainForm.Show();
    }

    // 4. Show notification
    public void ShowNotification(string title, string message)
    {
        _notificationCount++;

        // Update tray icon text
        _notifyIcon.Text = $"System Tray App - {_notificationCount} notifications";

        // Show balloon notification
        if (_contextMenu != null)
        {
            var balloonSettingsItem = (ToolStripMenuItem)_contextMenu.Items["Settings"]?.DropDownItems["Show Balloon Tips"];
            bool showBalloon = balloonSettingsItem?.Checked ?? true;

            if (showBalloon)
            {
                _notifyIcon.ShowBalloonTip(3000, title, message, ToolTipIcon.Info);
            }
        }

        Console.WriteLine($"Notification #{_notificationCount}: {title} - {message}");
    }

    // 5. Show system information
    private void ShowSystemInfo()
    {
        string info = $"System Information:\n\n" +
                     $"Operating System: {Environment.OSVersion}\n" +
                     $".NET Version: {Environment.Version}\n" +
                     $"Machine Name: {Environment.MachineName}\n" +
                     $"User Name: {Environment.UserName}\n" +
                     $"Processor Count: {Environment.ProcessorCount}\n" +
                     $"Working Directory: {Environment.CurrentDirectory}\n" +
                     $"System Directory: {Environment.SystemDirectory}";

        Console.WriteLine(info);

        // Show in message box
        MessageBox.Show(info, "System Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    // 6. Show about dialog
    private void ShowAboutDialog()
    {
        string aboutText = "System Tray Example Application\n\n" +
                          "Version: 1.0.0\n" +
                          "Author: Example Developer\n" +
                          "Description: Demonstrates system tray functionality\n\n" +
                          $"Notifications sent: {_notificationCount}\n" +
                          $"Application uptime: {DateTime.Now - _startTime:hh\:mm\:ss}";

        MessageBox.Show(aboutText, "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    private DateTime _startTime = DateTime.Now;

    // 7. Exit application
    private void ExitApplication()
    {
        DialogResult result = MessageBox.Show(
            "Are you sure you want to exit the application?",
            "Confirm Exit",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Question
        );

        if (result == DialogResult.Yes)
        {
            Console.WriteLine("Application exit confirmed");
            _notifyIcon.Visible = false;
            Application.Exit();
        }
    }

    // 8. Background task for periodic notifications
    private void StartBackgroundTask()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                await Task.Delay(30000); // Wait 30 seconds

                // Check if application is still running
                if (!_notifyIcon.Visible)
                    break;

                // Show periodic notification
                ShowNotification(
                    "Status Update",
                    $"Application is still running. Uptime: {DateTime.Now - _startTime:hh\:mm\:ss}"
                );

                // Clean up old notifications (keep only last 10)
                if (_notificationCount > 10)
                {
                    Console.WriteLine("Notification count reset to prevent overflow");
                    _notificationCount = 5;
                }
            }
        });
    }

    // 9. Handle application exit
    protected override void ExitThreadCore()
    {
        Console.WriteLine("System tray application is shutting down");

        if (_notifyIcon != null)
        {
            _notifyIcon.Visible = false;
            _notifyIcon.Dispose();
        }

        if (_contextMenu != null)
        {
            _contextMenu.Dispose();
        }

        base.ExitThreadCore();
    }

    // Main entry point
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("=== C# System Tray Examples ===\n");
        Console.WriteLine("Starting system tray application...");
        Console.WriteLine("Right-click the system tray icon to access the context menu.");
        Console.WriteLine("Double-click to show the main form.");
        Console.WriteLine("Press Ctrl+C in this console to exit the application.\n");

        try
        {
            // Enable visual styles
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Create and run the application context
            var applicationContext = new SystemTrayExamples();
            Application.Run(applicationContext);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error running system tray application: {ex.Message}");
        }
    }
}

// Alternative simple system tray example
class SimpleSystemTrayApp
{
    public static void RunSimpleExample()
    {
        Console.WriteLine("=== Simple System Tray Example ===");

        // Create simple notify icon
        using (var notifyIcon = new NotifyIcon())
        {
            notifyIcon.Icon = SystemIcons.Information;
            notifyIcon.Text = "Simple System Tray App";
            notifyIcon.Visible = true;

            // Create simple context menu
            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("Show Message", null, (s, e) =>
            {
                MessageBox.Show("Hello from system tray!", "Message", MessageBoxButtons.OK);
            });
            contextMenu.Items.Add("-");
            contextMenu.Items.Add("Exit", null, (s, e) =>
            {
                notifyIcon.Visible = false;
                Application.Exit();
            });

            notifyIcon.ContextMenuStrip = contextMenu;

            // Show initial notification
            notifyIcon.ShowBalloonTip(3000, "Simple App", "Simple system tray app started!", ToolTipIcon.Info);

            Console.WriteLine("Simple system tray app running. Close this window to exit.");

            // Keep application running
            Application.Run();
        }
    }
}

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

SVG Favicon and Icon Conversion Workflow

Prepare favicon, app icon, and web icon assets from SVG, PNG, ICO, JPG, and WebP sources with conversion and optimization checks.

Hub

Lead Generation Quiz Launch and Contact Handoff

Build and publish a product-fit quiz, test its tracked sharing path, and prepare a reviewed CSV of voluntary contacts without treating email as consent.

Hub

Private Habit Records: Backup, Restore and Sharing Review

Preserve a local habit journal, test JSON restoration without overwriting your working records, and prepare reviewed CSV or PNG copies without private notes.

Home
Tools3212
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Media

AVI to MP4 Converter

Convert AVI video files to MP4 format

Media

MP4 to AVI Converter

Convert MP4 video files to AVI format

Media

Batch Video Converter

Convert multiple video files between different formats like MP4, WebM, MKV, AVI, MOV with quality settings and batch processing

Media

Video Cutter

Cut and trim video clips with precision, supporting multiple formats and quality settings

Media

Video to APNG

Convert video clips to APNG (Animated PNG) format with transparency support and better quality than GIF

Media

Video to GIF Optimized

Convert videos to optimized GIF format with advanced compression settings

Media

Video to Image Sequence

Extract video frames as an image sequence with customizable frame rate, quality, and output format

Media

Video Trim

Quickly trim video clips - extract segments from videos with fast, lossless processing

C#

Windows Date and Time - C# Samples

Comprehensive C# date and time processing examples for Windows platform including DateTime, TimeSpan, TimeZone, and calendar operations

TypeScript

Web Desktop Features TypeScript Samples

Web TypeScript desktop-specific features examples including file dialogs, message boxes, and system tray

Testing

BDD with Cucumber - Behavior Driven Development

Comprehensive Cucumber BDD examples including feature files, step definitions, data tables, hooks, and advanced BDD patterns for collaborative development

Media

SVG Samples

Scalable Vector Graphics (SVG) samples demonstrating various SVG features and techniques

C#

Windows Image Processing - C# Samples

Comprehensive C# image processing examples for Windows platform including image manipulation, filtering, format conversion, and advanced computer vision operations

C++

Windows Serialization C++ Samples

Windows C++ data serialization examples including JSON serialization/deserialization and XML parsing