user1049697
user1049697

Reputation: 2509

C# and win32 API. Switch between two desktops. How to get back to the original desktop?

I'm writing a small program that creates a new Windows desktop, switches to it and waits a couple of seconds, and then switches back to the original desktop. I've managed to create and switch to the new desktop, but not back again to the original. I'm using the win32 API in C# and importing the DLLs. I thought GetDesktopWindow() would get me the handle to the original desktop, but it does not work for me.

Here is the code snippet I'm trying to get to work.

    public IntPtr createDesktop(string name)
    {
        return CreateDesktop(name, IntPtr.Zero, IntPtr.Zero, 0, (long)DESKTOP_ACCESS_MASK.GENERIC_ALL, IntPtr.Zero);
    }

    public IntPtr getCurrentDesktop()
    {
        return GetDesktopWindow();
    }

    public void switchDesktop(IntPtr desktop)
    {
        SwitchDesktop(desktop);
    }

    main()
    {
      IntPtr newDesktop = createDesktop("Test");
      IntPtr oldDesktop = getCurrentDesktop();
      switchDesktop(newDesktop);
      switchDesktop(oldDesktop);
    }

Upvotes: 2

Views: 1801

Answers (1)

Anders Abel
Anders Abel

Reputation: 69260

The Desktop Window is the Window that makes out the background of the desktop. It is not the same as the Desktop itself. You need to change getCurrentDesktop() to fetch the handle of the desktop itself, not a window on the desktop (although a special window).

I think that you can use GetThreadDesktop() to get the current desktop before switching to the new one.

Upvotes: 4

Related Questions