Windows 10 introduces Virtual Desktops. This new feature comes with a few recommendations. From the documentation:
Applications should avoid automatically switching the user from one virtual desktop to another. Only the user should instigate that change. To support this, newly created windows should appear on the currently active virtual desktop. Besides, if an application can reuse currently active windows, it should only reuse windows if they are on the currently active virtual desktop. Otherwise, a new window should be created.
If you want to reuse the currently active windows you need to detect if the current window is on the current virtual desktop. Windows provides the IVirtualDesktopManager interface to deal with virtual desktops. For this use case, we can use the IsWindowOnCurrentVirtualDesktop method to know if a window is on the current virtual desktop.
You can then use VirtualDesktopManager in your application to detect if a window is on the current desktop:
C#
privatestaticvoidMain()
{
var virtualDesktopManager = new VirtualDesktopManager();
var currentProcess = Process.GetCurrentProcess();
var processlist = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process process in processlist)
{
if (process.Id == currentProcess.Id)
continue;
if (process.MainWindowHandle != IntPtr.Zero)
{
if (virtualDesktopManager.IsWindowOnCurrentVirtualDesktop(process.MainWindowHandle))
{
// Activate the existing window and exit the current process
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
return;
}
}
}
// TODO actual application code
}
[DllImport("user32.dll")]
privatestaticexternboolSetForegroundWindow(IntPtr hWnd);