Barnamenevis.Net.RtlMessageBox.WindowsForms 1.0.1

dotnet add package Barnamenevis.Net.RtlMessageBox.WindowsForms --version 1.0.1
                    
NuGet\Install-Package Barnamenevis.Net.RtlMessageBox.WindowsForms -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Barnamenevis.Net.RtlMessageBox.WindowsForms" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Barnamenevis.Net.RtlMessageBox.WindowsForms" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Barnamenevis.Net.RtlMessageBox.WindowsForms" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Barnamenevis.Net.RtlMessageBox.WindowsForms --version 1.0.1
                    
#r "nuget: Barnamenevis.Net.RtlMessageBox.WindowsForms, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Barnamenevis.Net.RtlMessageBox.WindowsForms@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Barnamenevis.Net.RtlMessageBox.WindowsForms&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Barnamenevis.Net.RtlMessageBox.WindowsForms&version=1.0.1
                    
Install as a Cake Tool

Barnamenevis.Net.RtlMessageBox.WindowsForms

A Windows Forms-compatible RTL MessageBox implementation that wraps the native Win32 MessageBox with automatic Persian button text translation and custom font support.

📋 Overview

This library provides a drop-in replacement for the standard Windows Forms MessageBox with full RTL (Right-to-Left) support, automatic Persian button translation, and custom font integration. It uses Win32 hooks to modify the native MessageBox at runtime, ensuring compatibility with all Windows MessageBox features.

✨ Key Features

🌐 RTL & Persian Support

  • Automatic Persian Button Text: OK→تایید, Cancel→انصراف, Yes→بله, No→خیر, etc.
  • RTL Layout Options: Proper right-to-left reading and alignment
  • Win32 Integration: Uses native Windows MessageBox with custom modifications
  • Complete API Compatibility: Drop-in replacement for System.Windows.MessageBox

🎨 Font Management

  • Custom Font Application: Apply Persian fonts to all dialog elements
  • Runtime Font Configuration: Configure font family and size
  • Automatic Font Detection: Works with installed Persian fonts
  • Focus Management: Proper keyboard navigation and default button handling

🌟 Visual Features

  • Native Windows Theming: Respects system theme and appearance
  • System Icon Support: Standard Windows icons with proper scaling
  • Focus Indicators: Clear visual focus cues for keyboard navigation
  • Default Button Logic: Smart default button selection (OK/Yes preferred)

🚀 Quick Start

Basic Usage

using Barnamenevis.Net.RtlMessageBox.WindowsForms;

// Simple message
var result = RtlMessageBox.Show("سلام دنیا!");

// With title
var result = RtlMessageBox.Show("پيغام شما ارسال شد.", "موفقیت");

// Yes/No question
var result = RtlMessageBox.Show(
    "آیا مطمئن هستید که می‌خواهید ادامه دهید؟",
    "تأیید عملیات",
    MessageBoxButton.YesNo,
    MessageBoxImage.Question);

Font Configuration

// Configure font settings (typically in Form constructor or Main method)
RtlMessageBox.PreferredFontName = "Vazirmatn FD";
RtlMessageBox.PreferredFontPointSize = 10.0;
RtlMessageBox.ApplyCustomFont = true;

// Now all MessageBoxes will use the custom font
var result = RtlMessageBox.Show("این متن با فونت دلخواه نمایش داده می‌شود.");

API Reference

Static Properties

Property Type Default Description
PreferredFontName string "Vazirmatn FD" Font family name for dialog text
PreferredFontPointSize double 10.0 Font size in points
ApplyCustomFont bool true Enable/disable custom font application

Show Methods

All standard WPF MessageBox.Show overloads are supported for compatibility:

Ownerless Overloads
MessageBoxResult Show(string messageBoxText)
MessageBoxResult Show(string messageBoxText, string caption)
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, MessageBoxOptions options)
Owner-Aware Overloads
MessageBoxResult Show(Window owner, string messageBoxText)
MessageBoxResult Show(Window owner, string messageBoxText, string caption)
MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, MessageBoxOptions options)

⚙️ Technical Implementation

Win32 Hook Mechanism

The library uses a CBT (Computer-Based Training) Hook to intercept MessageBox creation:

  1. Hook Installation: Temporarily installs a thread-specific hook
  2. Dialog Detection: Identifies MessageBox windows by class name (#32770)
  3. Button Translation: Locates and retitles buttons with Persian text
  4. Font Application: Applies custom fonts to all child controls
  5. Focus Management: Sets proper default button and focus
  6. Cleanup: Removes hook and cleans up resources

Font Creation Process

// Creates a custom font using Win32 CreateFontIndirect
private static IntPtr CreateDialogFont(string faceName, double pointSize)
{
    // Calculate proper font height based on screen DPI
    // Create LOGFONT structure with Persian font settings
    // Return font handle for use with WM_SETFONT
}

Button Mapping Table

Button ID Persian Text English Equivalent
IDOK (1) تایید OK
IDCANCEL (2) انصراف Cancel
IDYES (6) بله Yes
IDNO (7) خیر No
IDRETRY (4) تلاش مجدد Retry
IDIGNORE (5) نادیده گرفتن Ignore
IDABORT (3) قطع Abort
IDTRYAGAIN (10) تلاش مجدد Try Again
IDCONTINUE (11) ادامه Continue

✅ Usage Examples

Error Handling

try
{
    // Some operation that might fail
    PerformOperation();
}
catch (Exception ex)
{
    RtlMessageBox.Show(
        $"خطا در انجام عملیات: {ex.Message}",
        "خطا",
        MessageBoxButton.OK,
        MessageBoxImage.Error);
}

User Confirmation

private void DeleteButton_Click(object sender, EventArgs e)
{
    var result = RtlMessageBox.Show(
        "آیا مطمئن هستید که می‌خواهید این فایل را حذف کنید؟\nاین عملیات قابل بازگشت نیست.",
        "تأیید حذف",
        MessageBoxButton.YesNo,
        MessageBoxImage.Warning);
    
    if (result == MessageBoxResult.Yes)
    {
        DeleteFile();
    }
}

Save Changes Prompt

private void FormClosing_Handler(object sender, FormClosingEventArgs e)
{
    if (HasUnsavedChanges)
    {
        var result = RtlMessageBox.Show(
            "تغییرات ذخیره نشده‌ای وجود دارد. آیا می‌خواهید آن‌ها را ذخیره کنید؟",
            "ذخیره تغییرات",
            MessageBoxButton.YesNoCancel,
            MessageBoxImage.Question);
        
        switch (result)
        {
            case MessageBoxResult.Yes:
                SaveChanges();
                break;
            case MessageBoxResult.No:
                // Continue closing without saving
                break;
            case MessageBoxResult.Cancel:
                e.Cancel = true; // Cancel the close operation
                break;
        }
    }
}

Information Display

private void ShowAbout()
{
    RtlMessageBox.Show(
        "نرم‌افزار مدیریت فایل\nنسخه 1.0.0\n\nتوسعه یافته توسط تیم برنامه‌نویس",
        "درباره برنامه",
        MessageBoxButton.OK,
        MessageBoxImage.Information);
}

🌈 Integration with Windows Forms

Form Designer Integration

This library works perfectly with Windows Forms Designer-created applications:

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        
        // Configure RTL MessageBox
        RtlMessageBox.PreferredFontName = "Vazirmatn FD";
        RtlMessageBox.ApplyCustomFont = true;
    }
    
    private void saveButton_Click(object sender, EventArgs e)
    {
        // Use RTL MessageBox instead of standard MessageBox
        RtlMessageBox.Show("فایل با موفقیت ذخیره شد.", "موفقیت");
    }
}

Global Configuration

Set up font configuration once in your application:

// In Program.cs or Main method
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    
    // Configure RTL MessageBox globally
    RtlMessageBox.PreferredFontName = "Vazirmatn FD";
    RtlMessageBox.PreferredFontPointSize = 9.0;
    RtlMessageBox.ApplyCustomFont = true;
    
    Application.Run(new MainForm());
}

📦 Requirements

  • .NET 8.0-windows or later
  • Windows Forms application
  • Windows 10/11 (Win32 API dependencies)

⚡ Advanced Features

Custom Default Button Logic

The library implements smart default button selection:

  • OK buttons are preferred over Cancel
  • Yes buttons are preferred over No
  • Focus and visual state are properly managed
  • Keyboard navigation follows RTL patterns

Memory Management

  • Font handles are properly created and destroyed
  • Hook cleanup prevents memory leaks
  • Thread-safe hook management
  • Exception handling prevents crashes

RTL Layout Options

The library automatically applies RTL options to the native MessageBox:

private static MessageBoxOptions AddRtl(MessageBoxOptions options)
{
    return options | MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign;
}

🤝 Integration with FontInstaller

Works seamlessly with the FontInstaller utility:

// In Program.cs
static void Main()
{
    // Install fonts at application startup
    try
    {
        var installedCount = FontInstaller.InstallApplicationFonts();
        if (installedCount > 0)
        {
            // Configure RTL MessageBox to use newly installed fonts
            RtlMessageBox.PreferredFontName = "Vazirmatn FD";
        }
    }
    catch
    {
        // Fall back to system fonts if installation fails
    }
    
    Application.Run(new MainForm());
}

⚠️ Important Notes

  1. Thread Safety: The hook is installed per thread, making it safe for multi-threaded applications
  2. Font Requirements: Custom fonts must be installed on the system or installed via FontInstaller
  3. Compatibility: Works with all Windows versions that support the Win32 MessageBox API
  4. Performance: Minimal overhead - hooks are only active during MessageBox display

🔗 See Also

Product Compatible and additional computed target framework versions.
.NET net6.0-windows7.0 is compatible.  net7.0-windows was computed.  net7.0-windows7.0 is compatible.  net8.0-windows was computed.  net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net9.0-windows7.0 is compatible.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0-windows7.0

    • No dependencies.
  • net7.0-windows7.0

    • No dependencies.
  • net8.0-windows7.0

    • No dependencies.
  • net9.0-windows7.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 197 10/2/2025
1.0.0 353 10/1/2025

Version 1.0.1:
- Long message text handling improved.
Version 1.0.0 - Multi-targeting support:
- Win32 MessageBox wrapper with RTL support
- Compatible with .NET 6.0, 7.0, 8.0, and 9.0 (Windows)
- Automatic Persian button text translation via hooks
- Custom font application to all dialog elements
- Full API compatibility with WPF MessageBox
- Real-time button text modification
- Proper focus and default button management