Reputation: 558
I've created a pop up window in c#. I have a button and when the user clicks the button the window pops up. My problem is that if the user happens to click the button multiple times, the window will be opened multiple times. Once the user has opened the window, I do not want the window to be opened again if the user clicks the button. Is this possible to achieve?
My make the window pop up like this:
PopUp myPopUp = new PopUp();
myPopUp.show();
I am using wpf.
Upvotes: 0
Views: 2807
Reputation: 25351
Like in-lucky said, the best option is to use ShowDialog
. However, if you don't want it to be a modal dialog, you can us Application.Current.Windows
which gives you the list of open forms in your applications. Then check if your form is in the list before you show it with your code. Something like this:
if(Application.Current.Windows.OfType<Window>()
.Where(x => x.Name == "myPopUpName").FirstOrDefault() == null){
PopUp myPopUp = new PopUp();
myPopUp.show();
}
Alternatively, if you don't want to hardcode the name of the form, you can do it like this:
PopUp myPopUp = new PopUp();
if(Application.Current.Windows.OfType<Window>()
.Where(x => x.Name == myPopUp.Name).FirstOrDefault() == null){
myPopUp.show();
}
But this wastes some resources because it creates a new copy of the form and then discards it if already open.
Upvotes: 0
Reputation: 8079
If the user needs to access the main window after the popup opened I would create a class member, that holds a reference to the popup and on closing the popup set that reference to null
:
PopPp myPopUp = null;
private void OpenPopUp()
{
if(myPopUp == null)
{
myPopUp = new PopUp();
myPopUp.Closed += (x,y) => { myPopUp = null; };
myPopUp.Show();
}
}
If the user does not need to interact with the main window, while the popup is opened just use ShowDialog
. It will prevent any input to the main window until the popup is closed:
PopUp myPopUp = new PopUp();
myPopUp.ShowDialog();
Upvotes: 5
Reputation: 29006
Best option is to use ShowDialog
instead for Show
, then the user need to close the popup in order to click the button again. so the code will be :
PopUp myPopUp = new PopUp();
myPopUp.ShowDialog();
Or else you have to disable the button after first click by using buttonName.Enabled = !buttonName.Enabled;
in this case you have to find the point at which button needs to enabled back.
Upvotes: 2