MS Access: Enhanced Message Box Replacement

Tuesday, May 20, 2008

technology02.png This project provides a custom and enhanced message box replacement for the default MsgBoxfound in Access. A Test database for Access 2007 is available at the bottom of this post. (Updated 12AUG2008.)

What’s wrong with the default MsgBox

The default message box in Access is sometimes useful to warn, inform or ask confirmation from the user.

Standard MsgBox

It has, however, a few drawbacks:

  • It is bland; the standard message box does not follow the currently selected Office 2007 scheme.
  • The amount of text it can display is limited. If you try to display too much the text will be truncated.
  • You can’t copy or save the content of the message being displayed.
  • Because message boxes are viewed as intrusive, people tend not to read them and end-up closing them before they realize it may have contained useful information.
  • It only displays plain text. You cannot format the message to draw attention to the key points.

Sometimes you need to display an important message or require users to take an action. Message boxes are not to be abused but they serve a useful purpose.

An enhanced message box

Rather than using the bland standard message box you can now have something a bit more customized.

Plain Text version of the enhanced custom message box under the Office Blue Colour Scheme:

Plaintex Enhanced Message Box

RichText version of the enhanced custom message box under the Office Black Colour Scheme:

RichText Enhanced Message Box

Here are the features of the enhanced message box:

  • It is entirely compatible with the standard one: just change MsgBox to Box using find and replace should be enough.
  • It allows the user to simply click on a button to copy the content of the message to the clipboard or to save it to a text file to a configurable default location.
  • It looks and feel like it belongs to the main application, following its colour scheme.
  • It attempts to prevent users from blindly closing the modal box without them making an effort to read the message: buttons will first be inactive for a configurable amount of time. It’s not a perfect solution, but it is quite effective.
  • There is a RichBox version that can display rich HTML content, not just plain text, so important parts of the message can be formatted in a useful way.
  • It is able to display large amount of data. While it’s not something you usually want, it may be useful for the message box to display more text in some situations (log or tracing information, legal documentation, etc).
  • Rather than sprinkling your code with “& vbCrLf & _” uglies, you can embed newlines in the text itself by using C-style “n” escape sequences that will automatically be transformed into the appropriate newlines. Makes for clearer code and less typing.
  • Because you get the source, you can easily customise the message box with new icons and colours to better match your overall application’s personality.
  • It is non-blocking: if your application forces users to log-off after a certain amount of inactivity, the enhanced message box will just close rather than prevent Access from closing like the standard MsgBox does. Of course, it’s up to you to decide how to handle that gracefully, if at all.
  • It properly displays the expected button captions based on the language of the operating system, so it behaves very much like the default MsgBox (for instance, it will properly display “Cancel” on English systems and “Annuler” on French ones).
  • It also properly plays the system sounds associated with the type of message. You can also enable or disable the sound effect as needed.

How to use it

Download the demo below and copy (drag & drop) the following into your application:

  • the FormDialog form,
  • the API_GetTextMetrics module,
  • the Dialog module.

If you rename the FormDialog, make sure you replace any occurrence to it in the code, in particular in the Dialog module.

Since the enhanced message box is just a replacement for the standard one, you just use it like you would use the MsgBox.
There are a few additional settings that can be used to change the behaviour of the enhanced message boxes.
One is that you can adjust the delay before the buttons become activated.
Another one is that you can enable or disable whether beeps should be played or not.
The last settings is the folder where we should save the content of the message when the user clicks the Save button on the message box.
These few settings make the enhanced message box more customizable.

Large text

The standard MsgBox cannot display much text. On the other hand, there is no real limitation to the amount of text the Box and RichBox can display.
When the amount of information is too much to fit the maximum allowed size for the message box the text will overflow and can be scrolled up/down as necessary.

Limitations of the RichBox

The RichBox version relies on the normal TextBox control’s ability under Access 2007 to display RichText wich is nothing more than lightweight HTML.
Because font size may be varying a lot in the message, it becomes very difficult to accurately predict the size of the box needed to display the whole message.
Short of implementing a complete HTML engine, we have to rely on some assumptions to display HTML.
The risk is that sometimes the content may not properly fit the TextBox control in some circumstances.
If you use the RichBox, thoroughly try displaying your messages and tweak the HTML as necessary to include additional lines or non-breaking spaces to ensure that the result looks good.
If you don’t overuse font size and don’t display in multiple fonts the RichBox should do the right thing most of the time.
Don’t overuse the RichBox to display colourful messages. There is a fine line between being informative and tasteless. Keep colours and formatting where it is useful.
I think that in most cases, the plain text version Box is more than enough.

How it works

The code makes extensive use of Win32 API calls.
Most of the hard work is done in the FomDialog class form. There is too much there to really go into the details but you are welcome to have a look at the commented code.
The code relies also on a utility function from Stephen Lebans used to calculate the size of of text. I have made some minor modification to that code so I would refer you to his original implementation if you are interested in calculating TextBox sizes for forms or reports.

In the code for the FormDialog, I re-implement some of the expected functionalities of the MsgBox: proper arrangement of the buttons, displaying of the appropriate icon, etc.
Once this is done, we calculate the size of the textbox needed to display the whole of the message.
In the case of RichText, we first use Application.PlainText() to convert the HTML into properly formatted plain text. We then calculate the Textbox size using a slightly larger font than needed as a way to ensure that the content of the RichText message will fit the box in most cases.
Once we know the size of the TextBox, we can easily resize the form to properly display the TextBox.
If there is too much text, we resize the form to its maximum permissible (70% or screen width and 90% of screen height) and change some of the visual cues to let the user know the text is overflowing.

One thing of note is the way the form is kept modal.
Rather than using DoCmd.OpenForm and DoCmd.Close I use the form as a class and create an instance manually (see the code in Dialog.Box and Dialog.Richbox). I keep this instance alive until I got the form’s result back.
If you are interested in knowing how the form is made modal, this is the code in FormDialog.ShowModal() what keeps the form open until the user clicks a button:
The Sleep() function is a Win32 API that stops the current process for the given number of milliseconds. This in effects hands back the control to the Operating System for a short time. That way the system is still responsive and does not consume resources when it’s just waiting for user input.

Sample database

You can download a sample database containing all the necessary code as well as a number of tests.
This version only contains the database in Microsoft Access 2007 accdb format.

Sample database testing form

DownloadDownload the EnhancedMsgBox01.zip (107KB), v1.1 containing the ACCDB database.

Code Updates

v1.1: 08AUG2008

  • Corrected code for DefaultButtonDelay (thanks to Geoffrey) (was referencing wrong variable, causing self-referencing code).
  • Corrected code for Box and RichBox to take the DefaultSavedTextFileFolder into account (the path was previously not passed onto the dialog boxes and the text file would always be created in the application folder instead of the one specified by DefaultSavedTextFileFolder)
  • Added license notice at top of source code.

v1.0: 20MAY2008

  • Original version

Resources

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.
Free for re-use in any application or tutorial providing clear credit is made about the origin of the code and a link to this site is prominently displayed where end-users can easily access it.

Entry Filed under  :  Database, MSAccess, Programming

27 Comments Add your own

  • 1. Edwin Blancovitch  |  June 5th, 2008 at 5:00 am

    WAO !!

    i cannot say more . . . this is extremely good . . .

    i saw other solutions but yours surpass all others, congratulations . . .

    keep on doing the good work . . .

  • 2. Renaud  |  June 7th, 2008 at 4:04 pm

    Thank you Edwin. There are plenty more that I’d like to do, just a matter of finding the time…

  • 3. Marvin  |  June 30th, 2008 at 2:00 pm

    Simply smart! Thank you, Sir!

  • 4. Anon  |  June 30th, 2008 at 11:59 pm

    Simply fantastic, great work, thank you!

  • 5. Ken Warthen  |  July 30th, 2008 at 10:14 pm

    Renaud,

    Your website was a real find. I love the enhanced message box utility for Access, as well as the modal dialogs with transparent backgrounds. These are awesome tools that help Access developers to create interfaces that have some visual appeal. Thanks so much for your efforts and generosity.

    Ken Warthen

  • 6. Renaud  |  July 30th, 2008 at 11:11 pm

    Thank you for your kind words, I’m glad you found some of these articles useful.

  • 7. Glenn  |  July 31st, 2008 at 6:13 pm

    Renaud,

    I have briefly looked over your custom message box concept and like what I see. I am curious, however, because unless I am mistaken you have implemented it in Access using standard modules rather than as a class. Is there any particular reason you didn’t create a class instead?

    Glenn

  • 8. Renaud  |  July 31st, 2008 at 6:56 pm

    Hi Glenn, I think the main reason I didn’t use a class was that I wanted a drop-in replacement for the standard MsgBox. Using a class would have required creating an instance of it either every time the box would be used, or stored somewhere in a module. Classes also become an issue as they cannot be instantiated directly from a library (the way I usually re-use code) and you must end-up having a class factory in a Module instead.

    It doesn’t mean it can’t be done. I just don’t think it bring anything useful doing it in a Class as opposed to a Module in this case.

    Maybe I’m wrong and there is a better way.

    In that case let me know :-)

  • 9. glenn  |  August 1st, 2008 at 12:26 am

    Renaud,

    Thanks for that. Your explanation makes perfect sense and I can’t think of a compelling reason to suggest that a class based alternative would be preferable. Code libraries are certainly the way to go for frequently used code.

    While using a class in this case doesn’t appear to offer an advantage over your standard module approach, you might be interested to know that there are a couple of ways to include classes in code libraries such that any application using the library can create instances of the relevant classes.

    Glenn

  • 10. Moo  |  August 1st, 2008 at 6:49 am

    This is rather awesome! Mind if I take a shot at back-grading it to Access 97?

  • 11. Renaud  |  August 1st, 2008 at 9:57 am

    @Glenn: I use a simple module that I call “ClassFactory” whose only purpose is to return an instance of the Classes in the library. Not sure if there is a better way.

    @Moo: please be my guest. I have been thinking about this recently but since I only have Access 2007 testing for older version is a bit of a challenge.

    Adapting the code to older versions should not be difficult if you stick to plain text. You will have to remove references to the “TextFormat” property of the txtMessage textbox as it is new in Access2007 and used to switch between plain text and rich text.

    As far as I know, the only way to bring rich text to older versions of Access is to use a webbrowser control.

    If you manage to convert it, please send me the updated database so I can host it here for all to find.

  • 12. Glenn  |  August 1st, 2008 at 4:25 pm

    Renaud,

    You can do without the module by manipulating the class module’s Instancing property. The catch is that the property sheet doesn’t allow the setting you need but you can run a single statement in the immediate window to do the job. See this post http://www.utteraccess.com/forums/showthreaded.php?Cat=&Number=1441683&page=&view=&sb=5&o=&vc=1

    Glenn

  • 13. Renaud  |  August 3rd, 2008 at 3:20 pm

    Hi Glenn, thanks for the tip!

  • 14. Moo  |  August 6th, 2008 at 6:33 am

    Renaud,

    I gave it a shot and without the RTF it just wouldn’t be the same; so I chose not to pursue it any further.

    The Access 2007 version is striking! Thanks!

    Moo

  • 15. Larry  |  August 6th, 2008 at 1:14 pm

    Get a compile error when trying to run it. “User defined Type not defined”……..Dim f As New Form_FormDialog. Have the same references checked in my Access 2007 VBA. Looks great. Would like to solve the problem to be able to use it. Thanks. Larry

  • 16. Alan Cossey  |  August 7th, 2008 at 4:02 am

    This is excellent. I’ve just added it to a new application and it looks far better and I like the ability to copy the message to the clipboard. It is also very good that it is non-blocking, i.e. I can now more easily chuck users out of my systems if I want, say, after a period of inactivity. A point that people might find useful is that rather than replace all instances of Msgbox in your code with the word “RichBox”, you can rename the new RichBox function as Msgbox. When your code then goes to call the Msgbox function, it then calls the new function, i.e. the old Msgbox gets overridden and the new function is called instead.

  • 17. Renaud  |  August 7th, 2008 at 2:07 pm

    @Larry: does this happen with the demo or in your application? Have you renamed the FormDialog? if that’s the case, make sure to change the line where you get the error to reflect the new name.
    Another possibility is security settings: if you’re getting a security warning when opening the file, make sure you open it from a Trusted location or some functions will be disabled.

    @Alan: it’s a good point and it could make replacement much easier, although I usually prefer to err on the side of caution and avoid overriding base functionality to avoid unintended consequences (and keep in line with the “element of least surprise” motto by making things explicit). :-)

  • 18. Geoffrey  |  August 8th, 2008 at 12:36 am

    Thanks for the great object!

    Out of Stack Space Error

    Occurs when modifying DefaultButtonDelay Try modifying the Enable Buttons In: field in sample form

    Problem occurs in module “Dialog”

    Reads:

    
    Public Property Let DefaultButtonDelay(delay As Long)
        If delay < 0 Then delay = 0
        DefaultButtonDelay = delay
    End Property
    

    Should read:

    
    Public Property Let DefaultButtonDelay(delay As Long)
        If delay < 0 Then delay = 0
        m_DefaultButtonDelay = delay
    End Property
    

  • 19. Larry  |  August 8th, 2008 at 7:01 am

    Compile error happens in my application which is in a Trusted location. Didn’t rename anything other than MsgBox changed to Box as instructed; for one of my boxes. Am I supposed to rename something else? The compile error highlights the following VBA code…… Dim f As New Form_FormDialog. Larry

  • 20. Renaud  |  August 8th, 2008 at 10:26 am

    @Geoffrey: good catch, I have updated the code. Thanks for notifying me.

    @Larry: still not sure why you’re getting this. Could you send me a zip file of your application so I can investigate? Send it to accessblog#nkadesign* (replacing # by @ and * by .com).

  • 21. Renaud  |  August 8th, 2008 at 3:20 pm

    @Larry,: you were missing the FormDialog in your application.
    I have updated the article to list the instructions on how to include the new code into your own application. I realised this was missing.

  • 22. Larry  |  August 9th, 2008 at 6:37 am

    Success! Enhanced Message Boxes are so much easier to identify when they pop up on the screen. The standard msgboxes are so bland they are almost camoflauged. Thank you very much, Larry

  • 23. Jack Stockton  |  August 9th, 2008 at 6:56 am

    Your code is way better that what I have written and really works as a replacement to the standard MsgBox function.

    Would like to suggest an enhancement….ability to specify customer text for two. I often have a business case where I am displaying a message box asking the user if they want to replace or open the existing.

  • 24. Jacques  |  August 12th, 2008 at 6:57 am

    I got stuck…

    A friend sent me the A2003 version, but it now appears that the RichText.ocx is blocked because of security reasons (apparently they deem it safe in A2007). I registered RICHTX32.ocx 6.0 (SP6) under references, but the 2003 mdb doesn’t compile: ‘acTextFormatHTMLRichText’ is not found - I found a registry-patch here: http://p2p.wrox.com/topic.asp?TOPIC_ID=10894 - doesn’t work on my pc.

    There is also a replacement, by Stephan Lebans: http://www.lebans.com/richtext.htm - registering it, didn’t help either.

    Also, the .png images don’t load - apparently they don’t get included on converting - could you include them separately?

    Any suggestions? I really would like to give this replacement a try - I do see its potential, but as I don’t have A2007, I can’t run it as such.

  • 25. Renaud  |  August 12th, 2008 at 3:51 pm

    @Jacques: I can only think of the webbrowser control as a replacement.
    May be too much overhead but it’s worth a try. I’ve sent you the icons by email. Let me know if you succeed :-)

  • 26. Andrew Craven Rohm  |  August 12th, 2008 at 6:10 pm

    Thank you. Pretty good work.

    There’s one extension I’d like to implement or see implemented, autowrap for long texts.

    There’s one slight problem with the code as it stands… The Default Buttons are not set properly. The Code for this looks fine until you notice that the buttons are named in the reverse order to their use. bt3 is used as button1, etcetera. The rest of the code reflects this, the Timer event which sets the default does not. Easy to change in the timer event just replace each occurence of bt1 with bt3 and bt3 with bt1.

    Thanks again, Andycr

  • 27. Stefan Reichelt  |  August 13th, 2008 at 10:17 pm

    Whow! What a great enhancement for my Access Tools. I just tried it and was really happy.

    Now there’s a variation I would love to see: A modified InputBox! Could you do that, too?

    Regards from Germany,

    Stefan

Leave a Comment

hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Most Recent Posts

Categories

Links