Tuesday, July 20, 2010

Minimize all Windows / Show Desktop

To achieve the same result as the shortcut "Show Desktop" (Win + D), namely minimizing all active windows, with C# we need to go a bit deeper in the system architecture and use an older COM object.
The Component Object Model is a platform technique to manage objects. In .Net these components are normally not used any more, but, as you see, from time to time they are still needed.
COM objects can be accessed by their GUID (Globally Unique Identifier) number, which identifies an object uniquely.
As this number is hard for us humans to use, furthermore there is the ProgID (Programmatic Identifier), which is more easy to understand (for example, names are something like Project.Class).
The ProgIDs are connected to GUIDs in the registry.

To now minimize all programs, we need the COM type Shell.Application. .Net can lookup a corresponding type from the registry with the function Type.GetTypeFromProgID(). Starting from this type we can create an instance of it using Activator.CreateInstance(). With InvokeMember() we can eventually call a function of this object.
But, enough of the theory, here simply the code for minimizing all windows and showing thus the desktop:

Type typeShell = Type.GetTypeFromProgID("Shell.Application");
object objShell = Activator.CreateInstance(typeShell);
typeShell.InvokeMember("MinimizeAll", System.Reflection.BindingFlags.InvokeMethod, null, objShell, null); // Call function MinimizeAll

In the call of InvokeMember() the first parameter says, that the function MinimizeAll is to be used. The 2nd one is a BindingFlag (here it says that the method is to be called). The 4th describes, that the object objShell is to be used for that.

5 comments: