Close a GUI.Window called from a GUI.SelectionGrid

I can’t figure out how to close a GUI.Window that it’s opened by a GUI.SelectionGrid.

My code is as follows:

void OnGUI () {
		selectionGridInt = GUI.SelectionGrid (new Rect (0, Screen.height - Screen.height/3, Screen.width, Screen.height/3), selectionGridInt, selectionStrings, selectionGridCols);

		if (selectionGridInt >= 0) {
			windowRect0 = GUI.Window (selectionGridInt, windowRect0, DoMyWindow, "Button " + (selectionGridInt + 1));
			}
	}

void DoMyWindow(int windowID) {
		if (GUI.Button (new Rect (10, 20, 100, 20), "Hello World")) {
				print ("Got a click in button " + windowID);
				}
		GUI.DragWindow(new Rect(0, 0, 10000, 10000));
	}

But if I add a boolean to toggle between rendered or not, It just shows all the time or not shows at all:

    private bool render = true;
    void OnGUI () {	
    		selectionGridInt = GUI.SelectionGrid (new Rect (0, Screen.height - Screen.height/3, Screen.width, Screen.height/3), selectionGridInt, selectionStrings, selectionGridCols);
    
    		if (render) {
    			if (selectionGridInt >= 0) {
    				windowRect0 = GUI.Window (selectionGridInt, windowRect0, DoMyWindow, "Button " + (selectionGridInt + 1));
    				ShowWindow ();
    				}
    			}
    	}
    
    	void DoMyWindow(int windowID) {
    		if (GUI.Button (new Rect (10, 20, 100, 20), "Hello World")) {
    				print ("Got a click in button " + windowID);
    				HideWindow();
    				}
    		
    		GUI.DragWindow(new Rect(0, 0, 10000, 10000));
    	}
    
    	public void ShowWindow() {
    		render = true;
    	}
    	
    	public void HideWindow() {
    		render = false;
    	}

How do I toggle from within the calls from SelectionGrid instead of a single Button?

The SelectionGrid is not ment to issue button down events but to provide a grid of buttons and one of them is selected. It’s like a radio-button-group if you’re more familiar with them. So once you click one of the buttons it will be active. Pressing the same button again won’t do anything since the buttons just provides a selection.

If you want to show the window whenever the selection is changed you need to save the old selection so you can tell when it has changed:

private bool showWindow = true;
void OnGUI ()
{
    int newSelection = GUI.SelectionGrid (new Rect (0, Screen.height - Screen.height/3, Screen.width, Screen.height/3), selectionGridInt, selectionStrings, selectionGridCols);
    if (newSelection != selectionGridInt)
    {
        ShowWindow();
    }
    selectionGridInt = newSelection;
    if (showWindow)
    {
        windowRect0 = GUI.Window (selectionGridInt, windowRect0, DoMyWindow, "Button " + (selectionGridInt + 1));
    }
}

void DoMyWindow(int windowID)
{
    if (GUI.Button (new Rect (10, 20, 100, 20), "Close"))
    {
        HideWindow();
    }
    GUI.DragWindow();
}
public void ShowWindow()
{
    showWindow = true;
}
public void HideWindow()
{
    showWindow = false;
}