Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Custom Message Box
 »  Home  »  Windows Development  »  Custom Message Box
Custom Message Box
by George Poth | Published  01/30/2004 | .NET Newbie Windows Development | Rating:
George Poth

I have been teaching English in Brazil since 1994 and always wanted to do more for learners than common textbooks can offer. This started with web sites that couldn't reach most students as computers and the Internet are not standard for most people in this country.

Computer tools to help Brazilian students learn a complex language like English are practically non-existent and so I sent some suggestions to software companies. Since Brazil is neither a target market for English textbooks nor for software of this kind, the rejection seemed natural.

As a result, I tried some free developer tools such as Borland's free C++ compiler, Free Pascal, and Envelope's Visual Basic. Envelope's Visual Basic, which is a Microsoft Visual Basic 1.0 clone and still available, suited my taste but I knew it was obsolete technology. In March 2003, I bought a copy of Microsoft Visual Basic .NET Standard and have been hopelessly contaminated with the programming virus ever since.

I mostly write programs for educational purposes. Having discovered the wonderful world of DirectX recently, I am diving into the most entertaining part of programming: games. One can connect teaching with pure entertainment, learning, and culture.

 

View all articles by George Poth...
Custom Message Box

Who needs a customized message box anyway? You - you just don't know it yet. Take a look at Figure 01. Is this the kind of message box you like? If yes, you can go on to the next tutorial because that's not what I'm going to talk about. What I am going to talk about is what you can see in Figure 02.

(Figure 01)

(Figure 02)

Unfortunately, Figure 02 can't show you that the text is actually blinking. But I think you got interested and will soon go beyond this very simple example.

Some time ago I was "globalizing" an application to be run on operating systems in three languages: English, German, and Portuguese. Making my application "speak" three languages was no big problem, until I came to the message boxes. I really couldn't get those message boxes to show messages in German and Portuguese. The only way around this was to build my own message boxes.

But why should you - a hobby programmer - worry about that? Think about the huge possibilities: you can speedily come up with message boxes matching the color of your program instead of the dull gray ones. Just think about the buttons: you aren't restricted to "Yes", "No", "Cancel", and the like. And why not put in a gradient background, or make the box round, oval, or whatever? Change the icon to something dynamic - .gif images make it possible.

You need to start a new project with two forms. The following charts give you the necessary specifications.

Control/ObjectSuggested NameSuggested Text
Form1frmStartupCustom Message Box
Button1btnShowSampleShow Sample

Control/ObjectSuggested NameSuggested TextDialogResult
Form2frmMessageBoxMy Message Box-
Label1lblMessage--
Button1btnYesGet me out of here!Yes
Button2btnNoNo way!No
Timer1tmrTextBlink--

If you want to have the same result as shown in Figure 02, you need to change some other properties, too.

Control/ObjectBackColorBorderStyleFontTextAlign
lblMessageFloralWhiteFixedSingleVerdana, Bold, ItalicMiddleCenter

Control/ObjectBackColorFont
btnYesFloralWhiteVerdana, Italic
btnNoFloralWhiteVerdana, Italic

If you prefer to have the controls in the same color as the gradient form, please set their BackColor property to transparent. Click the column on the right where it reads "BackColor" to activate the drop down box. Click the arrow button and then the Web tab. By default, "Transparent" is the first entry.

Code (Gradient Background):

Press F7 to go into code view and type Code 01 at the top of the file so that these become the very first lines of your file.

Code 01

'[Import drawing]
Imports System.Drawing.Drawing2D
'[/Import drawing]

Select "(Base Class Events)" from the Class Name list and "Load" from the Method Name list. Edit the generated code so that it looks like Code 02.

Code 02

Private Sub frmMessageBox_Load(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles MyBase.Load

    '[Paint gradient form]
    SetStyle(ControlStyles.AllPaintingInWmPaint Or _
                ControlStyles.DoubleBuffer Or _
                ControlStyles.ResizeRedraw Or _
                ControlStyles.UserPaintTrue)
    '[/Paint gradient form]

End Sub

Right below the region "Windows Form Designer generated code" is the place to type Code 03. I have used white and deep sky blue for the gradient background, but you can change this according to your taste.

Code 03

Protected Overrides Sub OnPaint_
    ByVal e As System.Windows.Forms.PaintEventArgs)

    '[Declare variables]
    Dim formGraphics As Graphics = e.Graphics
    Dim gradientBrush As New _
          LinearGradientBrush(New Point(00), New _
          Point(Width0), Color.WhiteColor.DeepSkyBlue)
    formGraphics.FillRectangle(gradientBrush_
      ClientRectangle)
    '[/Declare variables]

End Sub

Code (frmMessageBox):

Add Code 04 so that it goes before the "End Sub" of Code 02.

Code 04

    '[Enable the timer]
    tmrTextBlink.Enabled = True
    '[/Enable the timer]

Select "tmrTextBlink" from the Class Name list and "Tick" from the Method Name list. And if you have any other entry aside from "Tick" in the Method Name list, you should hurry to contact Microsoft - you have a yet undiscovered version of Visual Basic .NET. The comments should be sufficient so that you know what's going on.

Code 05

Private Sub tmrTextBlink_Tick(ByVal sender As Object_
    ByVal e As System.EventArgsHandles tmrTextBlink.Tick

    '[Declaration: must be static]
    Static NoText As Boolean
    '[/Declaration: must be static]

    '[If the boolean is true]
    If NoText = True Then
        '[/If the boolean is true]

        '[Erase the text]
        lblMessage.Text = ""
        '[/Erase the text]

        '[Make the boolean false]
        NoText = False
        '[/Make the boolean false]

        '[If the boolean is false]
    ElseIf NoText = False Then
        '[/If the boolean is false]

        '[Show the text in red]
        lblMessage.Text = "Do you want to exit the program?"
        lblMessage.ForeColor = Color.Red
        '[/Show the text in red]

        '[Make the boolean true]
        NoText = True
        '[/Make the boolean true]

    End If

End Sub

Save the changes by pressing Ctrl + S. Close the "frmMessageBox" so that the open windows won't confuse you.

Code (frmStartup):

Select "btnShowSample" from the Class Name list and "Click" from the Method Name list. Edit the generated code so that it looks like Code 06.

Code 06

Private Sub btnShowSample_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles btnShowSample.Click

    '[Show the custom message box]
    Dim frmMessage As New frmMessageBox()
    frmMessage.ShowDialog()
    '[/Show the custom message box]


    Select Case frmMessage.DialogResult

        '[If the user clicked "yes"]
    Case DialogResult.Yes
            '[/If the user clicked "yes"]

            '[Exit the program]
            Dispose(True)
            '[/Exit the program]

            '[If the user clicked "no"]
        Case DialogResult.No
            '[/If the user clicked "no"]

            '[Ignore it]
            Exit Sub
            '[/Ignore it]

    End Select

End Sub

Although I think that the comments will tell you most of the code, you should remember that "DialogResult.Yes" and "DialogResult.No" are just examples. You can change these dialog results according how you set the dialog result properties for the buttons in the "frmMessageBox". Take a look there and you will find all common message box dialog results.

Press F5 to run the program and then click the "Show Sample" button. Our message box will pop up showing you a flashy message. Click the button that reads "No Way!" and you'll get back to the startup form since the dialog result was set to "No" for this button. Click the button that reads "Get me out of here!" and the program will close since the dialog result for this button was set to "Yes".

Our custom message box is exactly like the ones you use(d) in your programs. The only difference is that we added color, less formal text on the buttons, and a flashy message. You don't have to put up with tedious message boxes in a modern program anymore. But watch out: some stiff and mentally old people won't be fond of this just as younger folks find the ordinary message boxes a real bore. Experiment with this and you will see that it can add to your program.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.6290322580645 out of 5
 186 people have rated this page
Article Score65924
Comments    Submit Comment

Comment #1  (Posted by I Schobert on 02/09/2004)

I like the idea of a custom Message Box, although it is only a form with certain properties set to resemble a message box. It gives developers some good ideas on how to manipulate Windows Forms.

I have only one suggestion:
To make this Message Box Form work under any conditions, it would required to capture the return of the x-button click. This can be either avoided by setting the form's ControlBox property to False, which will hide the min, max and x-buttons all together, or by adding another case to the select statement in the form that captures the dialog result. This would be the case DialogResult.Cancel. There, the developer could take appropriate action.

Thanks,

IS
 
Comment #2  (Posted by GP on 02/10/2004)

Thanks for the useful and necessary correction, Ingo. Very much appreciated.
 
Comment #3  (Posted by VbSeyyed on 02/14/2004)

Hi

Thank you for your best work. I is really a good idea. Thank you for sharing you knowlegde with others.

VbSeyyed
 
Comment #4  (Posted by whipp on 03/16/2004)

Is it possible to do something like this for a web (asp.net) application? The built-in web browser alert and confirm boxes are often very restrictive -- it would be great to be able to customize them.
 
Comment #5  (Posted by Alf Romani on 03/19/2004)

Your comment on the dull grey colour... well thats the system defined colors based on the user prefered settings. As a GUI programmer you should not deviate from this. Color blind people will never use your application if they can't customize the appliction colors for them (selfish aren't they). So if yo insist on using a differnt color and font scheme you must provide a method for the user to redefine them within your app. Probably better to leave well enough alone.
 
Comment #6  (Posted by GP on 03/20/2004)

I really didn’t get your criticism. First of all, my articles are for modern hobby programmers and not for color blind and/or old-fashioned people. You are basing your criticism on your personal opinion and on stuff you might have read or studied, but you obviously have not asked a single color blind person, have you?

My grandfather is ninety-eight years old and color blind. He loves that blinking text because “you pay more attention to it” which are his words. So your statement that "Color blind people will never use your application ..." is just the contrary of what I know from my grandfather and other color blind people around him. Maybe the ninety-year-old chap is more modern than you are.
 
Comment #7  (Posted by Grigore Dolghin on 06/10/2004)

In the same category fall the screen resizing from any custom application. It's user's monitor, user's eyes, user's desktop preferences, user's icons arrangement on desktop. A GUI developer shouldn't mess those.
 
Comment #8  (Posted by mzim on 07/03/2004)

[quote]
Maybe the ninety-year-old chap is more modern than you are.
[/quote]
LOL....maybe?
 
Comment #9  (Posted by ggandta on 07/06/2004)

George,

Need help with your Access Database Project. Having problems with mine.
 
Comment #10  (Posted by bravo659 on 08/25/2004)

It is a good idea to add robust dialog boxes, since the grey boxes are always the defaulting old age box. Instead of using different skins to the boxes, the coloration is good, and renders a good excite colors for users end. But there is one problem besides the blinking text, is awesome. The problem is that the startup frmShowSample will not popup when I press F5 or the debug/start. frmMessage is what popup. Clicking on the yes or no button has no effect to return to the frmShowSample. I believe there is a missing code to acquire the results. Email me if there is any explanation how the simple program works. I forgot the methodogy of the modal, and modeless exceptions in visual basic.net.
 
Comment #11  (Posted by mikeb on 09/16/2004)

Is there a way to resize the label and window if the text is too long to fit? This is easly done with a web dialog window, (modal) because you can read the height of the "label" container and resize the window.

The VB.net label however does not expand vertically if the text goes beyond the area available. It seems you would need to detect the amount of text, font size, number of lines, etc.

Any ideas?

vr mike
 
Comment #12  (Posted by mdProgrammer on 10/08/2004)

This looks like a nice messagebox. Can it be used in webforms?

Just a comment - if I were using extra controls for a messagebox, I would probably use another winform, and make it 'look like' a message box. Thing is, I can't exactly do that for an ASP webpage.
 
Comment #13  (Posted by an unknown user on 01/08/2005)
Rating
it's excellent for starting programming in vb.net.
thanx author of this code.
do post such good snisp
thanx for such free help
 
Comment #14  (Posted by an unknown user on 01/25/2005)
Rating
It´s very nice, u have changed a real old and boring message box. Thanks for ur support, and go foward on programming.
 
Comment #15  (Posted by Blair Bonnett on 01/26/2005)
Rating
Thanks, an excellent article. Exactly what I was looking for.

Re Comment 11: It is possible to measure the size of a string using the Graphics.MeasureString method. It does have a slight inaccuracy (see http://www.thecodeproject.com/cs/media/measurestring.asp ) but that can be fixed (see the comment "A better way to measure strings." in that article).

MSDN Documentation:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdrawinggraphicsclassmeasurestringtopic4.asp
 
Comment #16  (Posted by an unknown user on 02/23/2005)
Rating
it is better to give a zip file
 
Comment #17  (Posted by an unknown user on 03/23/2005)
Rating
As a learning programmer, I think this idea is excellent. Great job, and continue the good work.
 
Comment #18  (Posted by an unknown user on 03/23/2005)
Rating
As a learning programmer, I think this idea is excellent. Great job, and continue the good work.
 
Comment #19  (Posted by an unknown user on 04/20/2005)
Rating
Your response in Comment #6 really shows that you fundamentally do not understand good GUI design.
It is a poor practice to deviate from a user's chosen display properties if not necessary.
Now, if the program is built for a specific target audience and you know this is what they've requested, then fine - go for it.
But your arguments and defensive tone in that response show you really don't get it.
And, if the truth be known, the message box in Figure 2 is downright ugly.
Blinking, multi-color neon type message box with highly non-standard controls?
Any good experienced programmer would tell you this is poor GUI design.
As for being "modern" - what does that have to do with anything? If the end user has chosen to want "modern" then they will enable themes under XP or customize the color of their work area to suit their tastes whatever operating system they are using.
I laugh when I see programmers who always seem to think they know better than the end user what the end user wants and force them to re-learn new layouts, dialogs, etc. These are the type of apps that fall by the wayside becuase they are too frustrating or annoying to use. People like familiarity.
A good designer can design a beautiful interface and still maintain basic standards. Usability is usually much more important than aesthetics when it comes right down to it.
Whether you're a "hobby" programmer or not, you should practice good programming methods when it comes to developing apps for deployment.

Sorry for the long message, but your sarcastic answer to Comment #6 really got my goat. Thought I'd give you a little in return.
 
Comment #20  (Posted by an unknown user on 06/17/2005)
Rating
same as comment #1
 
Comment #21  (Posted by Subin Fernandez on 06/22/2005)
Rating
By seeing your alternate method for Message boxes, only one thing I would like to suggest: Please become a mature programmer as early as possible. And the article is not up to the mark as it should be for being published.

Post some better projects next time.

Your true wellwisher,

Subin Fernandez,
Bangalore, India.
 
Comment #22  (Posted by Brian on 06/24/2005)
Rating
Hello sir,
Can you help me out with me search button. i want to search from my datagrid. I have this key option if it is by name or by nickname then the user will type the keyword then the result will appear in the datagrid. help me =)
 
Comment #23  (Posted by an unknown user on 06/30/2005)
Rating
hehehe good
 
Comment #24  (Posted by an unknown user on 07/17/2005)
Rating
Man, look at the guy’s profile. Then look at the date the article was published. Should be clear the mate is a newbie himself. Some idiots didn’t get it and put in some ****ty comments (#19, #22, #25). Instead of insulting the man, why don’t you write something better?
 
Comment #25  (Posted by an unknown user on 07/22/2005)
Rating
Why bother? Does this have any application in the real world?
 
Comment #26  (Posted by an unknown user on 08/17/2005)
Rating
Excellent
 
Comment #27  (Posted by an unknown user on 10/25/2005)
Rating
Good idea
 
Comment #28  (Posted by an unknown user on 11/24/2005)
Rating
This is good to see such interesting message box. it is a fun in programming. thank u very much for this article.
 
Comment #29  (Posted by an unknown user on 01/01/2006)
Rating
when i am comment that code from Form load event,and press F5,same appereance display,without setStyle method,give me reason as possible as,
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.DoubleBuffer Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint, True)

my mail address is
Neelesh_neeto14@rediffmail.com
 
Comment #30  (Posted by an unknown user on 01/05/2006)
Rating
this is really a excellent codes which is really helpfull to me, i can implement a good graphicx huh!!!
 
Comment #31  (Posted by an unknown user on 01/27/2006)
Rating
Demonstrates that with a little bit of lateral thinking it is possible to add something really different to an application, a touch of class.
 
Comment #32  (Posted by an unknown user on 01/31/2006)
Rating
This is a good idea to have a customized message box although this is not changing the message box till givs idea to manipulate forms to use differently. Tgis idea can be used other purposes

thanks.
rabindrapatra
 
Comment #33  (Posted by an unknown user on 01/31/2006)
Rating
This is a good idea to have a customized message box although this is not changing the message box till givs idea to manipulate forms to use differently. Tgis idea can be used other purposes

thanks.
rabindrapatra
 
Comment #34  (Posted by an unknown user on 03/20/2006)
Rating
This is a good idea.Thanks
 
Comment #35  (Posted by an unknown user on 04/13/2006)
Rating
Nice Job.
Despite #19's inability to think on his/her own and out side the box. Creativity is the manstay of real programmers that have not turned into automatons them selves. Keep thinking and being creative. We don't need more people that think like "all the rest" again WTG! (Xanth)
 
Comment #36  (Posted by an unknown user on 06/09/2006)
Rating
While I agree that you shouldn't force deviation from the user's preference, there are several examples where it is considered OK. For instance, have you ever noticed that internet explorer and mozilla both have a gradient on the toolbar, going from a tannish color to the "ugly default grey"? Do you think the microsoft programmer who came up with that got scolded for deviating? Take a look at some of the newer programs coming out like Ad-Aware, a higly popular adware removal program, it's interface is completely deviated, yet, it's highly popular. How about all the instant messengers... Although I personally feel you should always give the user the choice to revert to the way they want it to look, it's not necessary in certain situations.

As far as how this can be used in the "real world"... this shows programmers how to create custom message boxes, not necessarily just a gradient or just flashing text, but how to make a form become a message box, in which you can do anything you need to do. This is helpful to anyone who has ever done any programming in VB...

The fact that you are here means that you use the internet to figure out how to do something you didnt know how to do, which is a huge benefit to us all, and people like the author of this article are nice enough to spend their time giving people like you information like this, so don't ever bash someone for doing this for you, even if you don't like their opinion about something.

Good job George, and Thanks.
 
Comment #37  (Posted by an unknown user on 11/01/2006)
Rating
A delightful little sample. Thank you.

Aaron
www.rmeai.com
 
Comment #38  (Posted by an unknown user on 04/02/2007)
Rating
Just what I was looking for! Thanks so much for posting this.
 
Comment #39  (Posted by an unknown user on 08/20/2007)
Rating
Please follow the Windows User Interface guidelines and use the standard boxes. There are many reasons, such as screen reader support, easy learning from standardization, and so on.
 
Comment #40  (Posted by Serge Baranovsky on 11/03/2007)
Rating
2 the standard UI zealots - I think you missing the point here - this article _is_ about making a custom message box if the reader _elects_ to...
 
Comment #41  (Posted by an unknown user on 12/12/2007)
Rating
Nice site
 
Comment #42  (Posted by an unknown user on 04/02/2008)
Rating
I found this article wonderful because I'm working with three languages also.
To the author, please email me, td0806@gmail.com
 
Comment #43  (Posted by an unknown user on 04/16/2008)
Rating
excellent!:)
 
Comment #44  (Posted by an unknown user on 12/01/2008)
Rating
getgeto
 
Comment #45  (Posted by an unknown user on 12/06/2008)
Rating
it´s a very interseting slution for what i was looking for, and it´s explained good and short
 
Comment #46  (Posted by an unknown user on 01/16/2009)
Rating
Great!
 
Comment #47  (Posted by an unknown user on 01/16/2009)
Rating
Great job!
 
Comment #48  (Posted by an unknown user on 04/20/2009)
Rating
Third Class Article...
 
Comment #49  (Posted by an unknown user on 04/22/2009)
Rating
BECAUSE ITS GAY
 
Comment #50  (Posted by an unknown user on 05/28/2009)
Rating
thanks
 
Sponsored Links