how the C # WinForm program prevents child windows from repeating pop-ups
Problem Description:
Clicking on the submenu in the main program menu will bring up the child window, but when the first child window has been popped, clicking on the submenu still brings up the second same child window. And what our manager wants is that when you click on the submenu, it doesn't create a new child window, it activates the first child window that has already been created and appears at the front (get focus).
Solution idea:
1, with ShowDialog instead of show.
ShowDialog causes the child window to mask all the functions of the parent window, that is, only the child window has focus. Sometimes it's convenient, but it's not what we need right now.
2, Mutex mode.
I do not know whether there is a sense of being overqualified, involving the program thread, I did not do the scrutiny.
3, set the global variables, in the production of new windows to make judgments. (This example uses this idea)
The key implementation code is shown in the following code section.
problem Recurrence:
Suppose that there is a main window Form1, which has a button btnnewform ("Generate a new Window"); Clicking the button will produce a new child window newform,newform The form has an introduction tag and a "Back" button. We hope that when you click on the "Create New Window" button and pop up the NewForm window, and then click the "Create New Window" button, no new child window will be generated, but the newly generated NewForm window reappears. The interface is shown in Figure 1, figure 2.
Figure 1 Form1 window
Figure 2 NewForm window
Reference Code:
private static NewForm NewForm;
<summary>
///Prevent child windows from recurring
///This is not showdialog, because it makes the parent window unavailable, there are many limitations and inconvenient;
///This example is the key to defining a global variable for a child window. And make a judgment
///</summary>
///<param name= "sender" ></param>///<param name=
"E" ></ param>
private void Btnnewform_click (object sender, EventArgs e)
{
if (NewForm = null | | newform.isdisposed)
{
newForm = new NewForm ();
Newform.show ();
}
else
{
newform.windowstate = formwindowstate.normal;
Newform.activate ();
}
reference materials:Reference 1