In Visual Studio C#, the MessageBox.Show will halt, but not lock, the current thread until the message window is closed.
One could even put it in the if statement and wait for the result.
In order to understand the mechanism behind it, I tried to make one of my own.
Let say there are 2 forms, MainForm and MsgForm. MsgForm is called from MainForm when a button is clicked. You could imagine that the MsgForm is my version of MessageBox.Show.
The key is for MainForm to wait for the MsgForm until a button in MsgForm is clicked.
Which is to say, to make it "modal".
I could manage it simply by calling MsgForm.ShowDialog() on MainForm, because ShowDialog() itself is modal.
But then I thought, what if I don't have that built-in mechanism!? How could I achieve the same thing!?
Since Show() isn't modal, so I think it's good to use it for test. If I manage to halt the program with Show(), then I succeeded in recreating MessageBox.Show.
I first tried to call AutoResetEvent.WaitOne() on MsgForm, it locked the whole thing! Same goes on MainForm's end.
But then I realized that the WaitOne() and the MsgForm must be called on "different threads" in order to not locking each other.
So I put the following code in MainForm:
private void button1_Click(object sender, EventArgs e)
{
if(Test())
{
label1.Text = "Done!";
}
}
private bool Test()
{
Thread t = new Thread(doTest);
t.Start();
Class1.ARE.WaitOne(); //ARE is a public static AutoResetEvent in Class1 for global usages.
return true;
}
private void doTest()
{
MsgForm frm = new MsgForm();
frm.Show();
}
And simply call Class1.ARE.Set(); in MsgForm's button click event.
Now it not only locked the whole thing, but also make the MsgForm disappear after a "flash".
I'm really at the end of my rope here!
Could somebody PLEASE be so kind and tell me where did I do wrong!?
Much appreciated!