Monday, June 17, 2019

Instantiating MessageBox

I came upon this thread about creating an instance of a messagebox where people were saying it can't be done because the class is sealed and only has a private constructor. Technically, you can create an instance of a message box, although I don't know why you would want to.

Because the class is sealed you cannot simply inherit a message box to extend it (that would be ideal). But you can use reflection to get an instance without a public constructor. You can then find a Show method and invoke it. There are many overloads of the Show method so you have to know which one you want. I'm going to use the simplest which just shows a message and an OK button.

The code looks like this.

ConstructorInfo ci = typeof(MessageBox).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
MessageBox mb = (MessageBox)ci.Invoke(null);
MethodInfo mi = typeof(MessageBox).GetMethod("Show", new Type[] { typeof(String) });
mi.Invoke(mb, new object[] { "Hello" });

And the result is, predictably, this.


No comments:

Post a Comment