Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a new window to be opened every time?

Tags:

window

wpf

I have a WPF application in which on a click of a menu item a window is opened. If the same menu item is clicked again when the window is already open, it is opening a new window but I don't want a new window to be opened every time.

What I need is, if the window is already open, the same window should be focused not a new window.

like image 998
U.G.P. Avatar asked Dec 28 '22 21:12

U.G.P.


2 Answers

//First we must create a object of type the new window we want the open.
NewWindowClass newWindow;

private void OpenNewWindow() {
    //Check if the window wasn't created yet
    if (newWindow == null)
    {
        //Instantiate the object and call the Open() method 
        newWindow= new NewWindowClass();
        newWindow.Show();
        //Add a event handler to set null our window object when it will be closed
        newWindow.Closed += new EventHandler(newWindow_Closed);
    }
    //If the window was created and your window isn't active
    //we call the method Activate to call the specific window to front
    else if (newWindow != null && !newWindow.IsActive)
    {
        newWindow.Activate();
    }
}
void newWindow_Closed(object sender, EventArgs e)
{
    newWindow = null;
}

I think this solve your problem.

Att,

like image 83
Arthur Barreto Avatar answered Jan 03 '23 16:01

Arthur Barreto


If your opened windows is used as simple dialog box you can use following code

window.ShowDialog();

when the dialog will show you cannot press any menu items unit you close this window

like image 39
Serghei Avatar answered Jan 03 '23 16:01

Serghei