Selenium provides the function windowhandle for the driver. this functions can be used to find out all the available windows in a driver and then can be switched if it is different from the previously opened window.
Below is the logic which i have used:
String a = driver.getWindowHandle();
Set<String> b = driver.getWindowHandles();
if(b.size() > 1){
for(String windowHandle : b)
{
if(windowHandle.equals(a))
{
//Do Nothing
}
else
{
driver.switchTo().window(windowHandle);
}
}