A great thing about being able to use C# code in Grasshopper is the ability to access other C# libraries and functions that we wouldn’t normally think of when using Grasshopper.
The message box is a good example of this, and can be a very simple and useful way of interacting with your user.
We can add a message box with a single line of C# in the C# component.
if(System.Windows.Forms.MessageBox.Show("If you're happy and you know it, clap your hands", "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK) A = "clap clap";
This gives us something like this:
Another nice thing about message boxes is, like in ‘regular’ C# programming, we can also get a response from the message box. If I hit ‘OK’, the output A changes:
This happens because we selected MessageBoxButtons.OKCancel. We then said that if the response is equal to DialogResult.OK then we should output ‘clap clap’ to A.
Creating our own message box
The basic structure to construct our own message box is:
System.Windows.Forms.MessageBox.Show("text","title", MessageBoxButtons.OKCancel);
We can choose a range of standard message boxes. When we create our message box, we can choose from one of 6 button combinations:
We can then respond to whatever button the user presses by writing an if statement corresponding to each of the buttons we have chosen:
So if we want the code to respond to the user’s choice, we will end up with something of the form:
if(System.Windows.Forms.MessageBox.Show("text","title",MessageBoxButtons.OKCancel) == DialogResult.OK) DoSomething();
Creating an input box
It is even possible to create an input box (i.e. a message box with a space for the user to type something), though it is slightly hacky and doesn’t look so good. It’s hacky because it’s technically not implemented for C#, and we are using the flexibility of .NET to access a library that was intended to be used with VB.
The class you need is in the VisualBasic namespace:
if(Microsoft.VisualBasic.Interaction.InputBox("If you're happy and you know it...", "What are you gonna do?", "enter response here", 100, 100) == "clap your hands") A = "clap clap";
…and as you’d expect, if you type “clap your hands”, we will get a response in A:
Thanks to this forum post for the input box code