Click here to Skip to main content
13,295,472 members (29,880 online)
Click here to Skip to main content
Add your own
alternative version


97 bookmarked
Posted 13 Apr 2007

Localizing System MessageBox

, 2 May 2007
Rate this:
Please Sign up or sign in to vote.
A simple class that allows customizing system's MessageBox window buttons
Screenshot - Article.gif


In our days, most applications must have a certain degree of localizability. More than often, I find myself in need for a component capable of showing simple messages, as the system MessageBox does, but capable of localization. There are tons of samples on how such a component can be implemented, but such a task is somewhat bigger than its purpose. On the other hand, you may already use components that use the system message box, which you cannot or just don't want to change. So, I implemented a static class named MessageBoxManager that is capable of setting the text of the system MessageBox buttons for all message boxes shown via the System.Windows.Forms.MessageBox.Show() method call.

Using the Code

This is really simple. Just add the MessageBoxManager class to your project, or include a reference to MessageBoxManager.dll, and follow the sample below:

static void Main()
    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Cancel = "Noway";
    MessageBox.Show("This is a message...","Test",MessageBoxButtons.OKCancel);


static void Main()
    System.Threading.Thread.CurrentThread.CurrentUICulture = 
				new System.Globalization.CultureInfo("ro");

    //Set button text from resources
    MessageBoxManager.OK = LocalResource.OK;
    MessageBoxManager.Cancel = LocalResource.Cancel;
    MessageBoxManager.Retry = LocalResource.Retry;
    MessageBoxManager.Ignore = LocalResource.Ignore;
    MessageBoxManager.Abort = LocalResource.Abort;
    MessageBoxManager.Yes = LocalResource.Yes;
    MessageBoxManager.No = LocalResource.No;

    //Register manager

    Application.Run(new Form1());

The MessageBoxManager implementation uses windows hooks internally. Whenever the application shows a Windows message box, MessageBoxManager changes its buttons' text accordingly.

The properties of the MessageBoxManager can be changed at any time. If you wish to change them, you don't have to unregister.

When multiple GUI threads are used, it is important to know that MessageBoxManager.Register() and MessageBoxManager.Unregister() work on a thread basis. Therefore the MessageBoxManager.Register() must be called for each GUI thread individually. Please note that buttons text cannot be set on a thread basis, these stand for all running threads.

How It Works

MessageBoxManager basically uses the Win32 API. Please see the code, it is pretty straightforward.

To access Win32 API from .NET, you need to make use of SecurityPermission attribute:

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]

You will need to declare the API functions you are going to use as follows:

private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

Now, let's see the Register() method:

private static HookProc hookProc;
private static EnumChildProc enumProc;
private static IntPtr hHook;

/// <summary>
/// Enables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// MessageBoxManager functionality is enabled on current thread only.
/// Each thread that needs MessageBoxManager functionality has to call this method.
/// </remarks>
public static void Register()
    if (hHook != IntPtr.Zero)
        throw new NotSupportedException("One hook per thread allowed.");
    hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, 
		IntPtr.Zero, AppDomain.GetCurrentThreadId());

Register() method does only one thing, it registers a windows hook for intercepting windows messages after they have been processed by the window procedure. Please note the ThreadStatic attribute for the hook handle. It ensures that the variable value is unique for each thread. hHook will store for each thread a different handle.

The intercepting callback is the MessageBoxHookProc method.

private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    if (nCode < 0)
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure
				(lParam, typeof(CWPRETSTRUCT));
    IntPtr hook = hHook;
    if (msg.message == WM_INITDIALOG)
        int nLength = GetWindowTextLength(msg.hwnd);
        StringBuilder className = new StringBuilder(10);
        GetClassName(msg.hwnd, className, className.Capacity);
        if (className.ToString() == "#32770")
            EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
    return CallNextHookEx(hook, nCode, wParam, lParam);

We are interested only in WM_INITDIALOG messages and only for windows of class "#32770" which is a special window class that messagebox window belongs to.

Once we intercepted the right message, we can start processing. This means enumerating all child windows, locating buttons and changing button text as we need.

private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
    StringBuilder className = new StringBuilder(10);
    GetClassName(hWnd, className, className.Capacity);
    if (className.ToString() == "Button")
        int ctlId = GetDlgCtrlID(hWnd);
        switch (ctlId)
        case MBOK:
            SetWindowText(hWnd, OK);
        case MBCancel:
            SetWindowText(hWnd, Cancel);
        case MBAbort:
            SetWindowText(hWnd, Abort);
        case MBRetry:
            SetWindowText(hWnd, Retry);
        case MBIgnore:
            SetWindowText(hWnd, Ignore);
        case MBYes:
            SetWindowText(hWnd, Yes);
        case MBNo:
            SetWindowText(hWnd, No);
    return true;

We identify the buttons based on their dialog control ID. OK is 1, Cancel is 2, etc. This can be easily found using the Spy++ utility that came with Visual Studio.

Is There Anything More?

Yes, actually there is. This "#32770" window class is not used only for MessageBox windows but also for the system open file window, print window, and more. If you need to use more system windows in your application but you have no better option to localize them than the one described in this article, you may extend the MessageBoxManager class to handle these windows too. All you need to do is to identify the dialog controls ID for the window labels using Spy++ utility, and add them in the MessageBoxEnumProc switch statement. You will find it very convenient that the dialog IDs for the same control in different windows are identical and unique. Setting the OK button text for the message box covers all ok buttons for all system windows.

Why Not Let OS Handle It by Setting the Proper Culture?

This works only if the desired language is installed on the system. Some people in some countries cannot, or prefer not to use the language packs provided by Microsoft. According to Microsoft, they only cover 80% of the UI. Also, if the native language of your users is not widely spread, the chance that the rest of the applications they use to be localized for their language is quite low. For these applications, they would see mixes such as texts in English but buttons in their own language, which may be disgracefully enough to avoid installing the language pack.

However, if there exists a language pack for your customers' native language, although for practical reasons I believe it is not always indicated to have it installed, I believe the text translation should be taken from there. This is done so that your application will look similar to the rest, if by chance the pack is or will be installed on the user's machine.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alex C. Duma
Software Developer (Senior)
Romania Romania
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionExcellent Coding Pin
TheSilverFox29-Nov-17 15:21
memberTheSilverFox29-Nov-17 15:21 
GeneralMy vote of 5 Pin
Casper Kalimero29-May-17 4:51
memberCasper Kalimero29-May-17 4:51 
QuestionDetecting closure using X at the top Pin
Kamran Kazemi7-May-17 23:11
memberKamran Kazemi7-May-17 23:11 
QuestionCan I sign the MessageBoxManager.dll generated from your source code? Pin
Member 47699232-Mar-17 0:57
memberMember 47699232-Mar-17 0:57 
QuestionUnfortunately doesn't work on Windows CE 6.0 :( Pin
Member 125045695-May-16 3:38
memberMember 125045695-May-16 3:38 
SuggestionEnhancement Pin
Jeronymite12-Apr-16 23:04
memberJeronymite12-Apr-16 23:04 
Praisegood guide Pin
nealee17-Feb-16 21:16
membernealee17-Feb-16 21:16 
PraiseThank you Pin
demon4078-Nov-15 22:01
memberdemon4078-Nov-15 22:01 
PraiseVote 5 Pin
@cromix.net30-Oct-15 15:06
member@cromix.net30-Oct-15 15:06 
QuestionIs there a way to keep the original keyboard shortcuts? Pin 3:22 3:22 
AnswerRe: Is there a way to keep the original keyboard shortcuts? Pin
Alex C. Duma30-Sep-14 9:12
memberAlex C. Duma30-Sep-14 9:12 
GeneralRe: Is there a way to keep the original keyboard shortcuts? Pin 20:58 20:58 
GeneralRe: Is there a way to keep the original keyboard shortcuts? Pin
Alex C. Duma1-Oct-14 10:43
memberAlex C. Duma1-Oct-14 10:43 
QuestionWorks like a charm, but ... Pin
laus773-Sep-14 5:55
memberlaus773-Sep-14 5:55 
QuestionNew labels for buttons not shown with MessageBoxOptions.DefaultDesktopOnly option Pin
Member 252452719-Aug-14 19:42
memberMember 252452719-Aug-14 19:42 
GeneralMy vote of 5 Pin
Member 105233047-Aug-14 1:01
memberMember 105233047-Aug-14 1:01 
GeneralThanks Pin
Member 109947645-Aug-14 22:58
memberMember 109947645-Aug-14 22:58 
GeneralReally nice Pin
Dycz22-Jul-14 5:09
professionalDycz22-Jul-14 5:09 
GeneralMy vote of 1 Pin
Nathan Phillip Brink15-Jul-14 6:12
memberNathan Phillip Brink15-Jul-14 6:12 
GeneralRe: My vote of 1 Pin
Alex C. Duma15-Jul-14 8:26
memberAlex C. Duma15-Jul-14 8:26 
GeneralMy vote of 5 Pin
laus773-Jul-14 22:44
memberlaus773-Jul-14 22:44 
Suggestionworks fine Pin
raydoman25-May-14 17:48
memberraydoman25-May-14 17:48 
QuestionThank you Pin
Member 1071152330-Mar-14 20:24
memberMember 1071152330-Mar-14 20:24 
QuestionGreat Pin
Hadi Barak24-Mar-14 22:36
memberHadi Barak24-Mar-14 22:36 
Questiongreat work Pin
Member 1043185828-Nov-13 1:19
memberMember 1043185828-Nov-13 1:19 
SuggestionWord of caution Pin
ahmd018-Jun-13 10:33
memberahmd018-Jun-13 10:33 
GeneralRe: Word of caution Pin
Alex C. Duma20-Jun-13 1:26
memberAlex C. Duma20-Jun-13 1:26 
GeneralMy vote of 5 Pin
Raul Iloc12-Jun-13 22:15
professionalRaul Iloc12-Jun-13 22:15 
QuestionCan I use this code in my project ??? Pin
serkan_serkan26-Mar-13 0:10
memberserkan_serkan26-Mar-13 0:10 
AnswerRe: Can I use this code in my project ??? Pin
Alex C. Duma26-Mar-13 1:41
memberAlex C. Duma26-Mar-13 1:41 
GeneralRe: Can I use this code in my project ??? Pin
serkan_serkan26-Mar-13 4:01
memberserkan_serkan26-Mar-13 4:01 
Generalthank you Pin
serkan_serkan26-Mar-13 0:01
memberserkan_serkan26-Mar-13 0:01 
GeneralMy vote of 5 Pin
tibi2252-Dec-12 1:22
membertibi2252-Dec-12 1:22 
GeneralMy vote of 5 Pin
mr.mabo24-Oct-12 5:12
membermr.mabo24-Oct-12 5:12 
QuestionError in MessageboxManager Pin
Saridakis Manolis13-Oct-12 23:57
memberSaridakis Manolis13-Oct-12 23:57 
GeneralMy vote of 5 Pin
alaalah1-Sep-12 11:53
memberalaalah1-Sep-12 11:53 
GeneralMy vote of 5 Pin
JasonMSA1-Feb-11 5:19
memberJasonMSA1-Feb-11 5:19 
QuestionModifying class to work with Syncfusion MessageBoxAdv? Pin
maria stein11-May-10 2:03
membermaria stein11-May-10 2:03 
AnswerRe: Modifying class to work with Syncfusion MessageBoxAdv? Pin
Huyh7-Feb-12 23:28
memberHuyh7-Feb-12 23:28 
Jokethank you very much Pin
doanhathanh4-Dec-09 8:46
memberdoanhathanh4-Dec-09 8:46 
NewsVery important Note Pin
amostafa847-Nov-09 2:56
memberamostafa847-Nov-09 2:56 
QuestionHow to size buttons to text? Pin
_dog9-Jul-09 12:08
member_dog9-Jul-09 12:08 

I'd like to compliment you on the usefulness and simplicity of the MessageBoxManager class. I like the fact that it uses the standard MessageBox instead of a custom Form, which many of the alternative postings I've seen do, so it can use standard MessageBox options, like overriding Right-To-Left, depending on the language.

I have found a couple of issues, and I'd like to get your opinion on these:

1. Is there a way to resize the buttons to the text?

I am using this to replace Yes/No/Cancel button text, for example:

MessageBoxManager.Yes = "Open for editing";
MessageBoxManager.No = "Open in read-only mode";

The button size is not sized to the text. Is there a way to autosize the overriden window?

2. Is there a way to have MessageBoxManager.Unregister() reset default button text? I have found I am not able to subsequently reuse the standard MessageBox buttons without providing text for previously overridden text. For example, if I override the Cancel button for one MessageBox text as:

MessageBoxManager.Cancel = "Don't change anything";

I can use it for that MessageBox. And after MessageBoxManager.Unregister() I can use the standard MessageBox, this is all fine. But in the same application if I want to use MessageBoxManager with another MessageBox that does NOT override the Cancel button, I still see the overridden Cancel button text, but in this new MessageBox, I would like to use the default Cancel button text provided by the OS.

AnswerRe: How to size buttons to text? Pin
dumaal10-Jul-09 0:19
memberdumaal10-Jul-09 0:19 
Generaldownload the source code Pin
ronitrom5-May-09 22:15
memberronitrom5-May-09 22:15 
GeneralRegarding licence terms Pin
deepa.abhyankar5-Apr-09 20:50
memberdeepa.abhyankar5-Apr-09 20:50 
GeneralRe: Regarding licence terms Pin
zipperle16-May-09 3:48
memberzipperle16-May-09 3:48 
QuestionWhat changes I have to make to work in a Device Application? Pin
sotero.mauricio2-Apr-09 9:27
membersotero.mauricio2-Apr-09 9:27 
QuestionIs #32770 is constant in any windows os version? Pin
Eliram Benitah16-Mar-09 23:42
memberEliram Benitah16-Mar-09 23:42 
GeneralThank you very much! Pin
Eliram Benitah16-Mar-09 11:02
memberEliram Benitah16-Mar-09 11:02 
GeneralThanks! Pin
Linoge-Fly4-Mar-09 1:37
memberLinoge-Fly4-Mar-09 1:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 2 May 2007
Article Copyright 2007 by Alex C. Duma
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid