Click here to Skip to main content
15,867,771 members
Articles / Desktop Programming / WPF
Tip/Trick

MessageBox Problem with Large Strings

Rate me:
Please Sign up or sign in to vote.
4.53/5 (6 votes)
5 Apr 2021CPOL1 min read 7.7K   76   6   8
When a string longer that 65536 is shown using a message box, the result might be unexpected.
In this tip, you will see what happens when a string longer that 65536 is shown using a message box. The result might be unexpected.

Introduction

A message box is designed to show a small amount of text with a few choices that the user can choose from. However, in some extreme or erroneus cases, the text might grow very long so what happens in such situation.

It seems that the message box has a limitation of 65536 characters for the text. That seems reasonable since that amount of text cannot be shown anymore because the window flows over the screen borders. One would expect an exception to be thrown in this case but what actually happens is that the message box is not shown, no exception is raised and the result for the message box is unexpected.

Test Case

First, let's have a small class providing the long string, like this:

C#
/// <summary>
/// Class to provide message box string
/// </summary>
public static class MessageString {

   private readonly static string baseString = @"Lorem ipsum dolor sit amet, 
   consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et 
   dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco 
   laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in 
   reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
   Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia 
   deserunt mollit anim id est laborum.

Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium 
doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore 
veritatis et quasi architecto beatae vitae dicta sunt, explicabo.Nemo enim ipsam 
voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur 
magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, 
qui do lorem ipsum, quia dolor sit amet consectetur adipisci velit, sed quia non 
numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat 
voluptatem.Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis 
suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum 
iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, 
vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?  At vero eos et 
accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum 
deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati 
cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, 
id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita 
distinctio.Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, 
quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, 
omnis dolor repellendus.Temporibus autem quibusdam et aut officiis debitis aut rerum 
necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae 
non recusandae.Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis 
voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
";
   /// <summary>
   /// Unlimited string
   /// </summary>
   public readonly static string UnlimitedString;

   /// <summary>
   /// Static constructor
   /// </summary>
   static MessageString() {
      for (int counter = 0; counter < 35; counter++) {
         UnlimitedString += baseString;
      }
   }

   /// <summary>
   /// Limited version of the string
   /// </summary>
   public static string LimitedString =>
      UnlimitedString.Length > 65536 
      ? UnlimitedString.Substring(0, 65535) 
      : UnlimitedString;
}

Now we can use this class to test the behaviour in different scenarios. For example, using C# and WPF, the code could look like:

C#
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
   public MainWindow() {
      InitializeComponent();
   }

   private void Limitless_Click(object sender, RoutedEventArgs e) {
      this.ShowMessage(MessageString.UnlimitedString);
   }

   private void Limited_Click(object sender, RoutedEventArgs e) {
      this.ShowMessage(MessageString.LimitedString);
   }

   private void ShowMessage(string text) {
      MessageBoxResult result;

      Mouse.OverrideCursor = Cursors.Wait;
      result = MessageBox.Show(text, 
                               "Message", 
                               MessageBoxButton.YesNoCancel, 
                               MessageBoxImage.Question, 
                               MessageBoxResult.Yes);
      MessageBox.Show($"Result was {result}", "Result", MessageBoxButton.OK);
      Mouse.OverrideCursor = null;
   }
}

Equally using Visual Basic.NET with Forms could look like:

VB.NET
Public Class Form1
    Private Sub Limitless_Click(sender As Object, e As EventArgs) Handles Limitless.Click
        Me.ShowMessage(MessageString.UnlimitedString)
    End Sub

    Private Sub Limited_Click(sender As Object, e As EventArgs) Handles Limited.Click
        Me.ShowMessage(MessageString.LimitedString)
    End Sub
    Private Sub ShowMessage(text As String)
        Dim result As DialogResult

        Application.UseWaitCursor = True
        result = MessageBox.Show(text, _
                                 "Message", _
                                 MessageBoxButtons.YesNoCancel, _
                                 MessageBoxIcon.Question, _
                                 MessageBoxDefaultButton.Button1)
        MessageBox.Show($"Result was {result}", "Result", MessageBoxButtons.OK)
        Application.UseWaitCursor = False
    End Sub
End Class

So What About the Result

As mentioned, the result of the message box is unexpected. If you try the test code where the message box has three buttons, Yes, No, and Cancel and the default button is Yes. When the unlimited text is passed to the message box, the result of the question is No (again, without actually showing the question).

Conclusion

So, if you have a situation where the text to be shown in a message box could grow long, remember to limit the text to some reasonable length. Otherwise, you may end up in peculiar situations and get wrong answers from UI.

History

  • 5th April, 2021: Created

License

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


Written By
Architect
Europe Europe
Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pin
Rusty Bullet7-Apr-21 3:34
Rusty Bullet7-Apr-21 3:34 
GeneralMy vote of 5 Pin
Member 137041436-Apr-21 22:53
Member 137041436-Apr-21 22:53 
QuestionSame on Native Win32 MessageBox API Pin
TobixDS6-Apr-21 2:14
TobixDS6-Apr-21 2:14 
QuestionWrong conclusion Pin
dandy725-Apr-21 4:28
dandy725-Apr-21 4:28 
AnswerRe: Wrong conclusion Pin
Kevin Marois5-Apr-21 5:35
professionalKevin Marois5-Apr-21 5:35 
AnswerRe: Wrong conclusion Pin
Wendelius5-Apr-21 6:25
mentorWendelius5-Apr-21 6:25 
GeneralRe: Wrong conclusion Pin
dandy725-Apr-21 6:51
dandy725-Apr-21 6:51 
Then your conclusion:


Quote:
if you have a situation where the text to be shown in a message box could grow long, remember to limit the text to some reasonable length



...is at odds with your introduction. The conclusion suggests that it should be allowed to grow, but to a limit. What is that limit? That's subjective. What I'm saying is that you shouldn't be trying to find what that threshold might be - a long, detailed message isn't something for the user to read to begin with, so "finding that limit" is the wrong problem to solve. Log it, but display something else altogether for the user. Your introduction agrees with that.

I hope that distinction is clearer.
AnswerRe: Wrong conclusion Pin
#realJSOP5-Apr-21 8:50
mve#realJSOP5-Apr-21 8:50 

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.