Minimizing all open windows in C#

anonymous coward picture anonymous coward · Apr 24, 2009 · Viewed 21k times · Source

I saw this C++ code on a forum which minimizes all open windows

#define MIN_ALL        419
#define MIN_ALL_UNDO   416

int main(int argc, char* argv[])
{
    HWND lHwnd = FindWindow("Shell_TrayWnd",NULL);
    SendMessage(lHwnd,WM_COMMAND,MIN_ALL,0);
    Sleep(2000);
    SendMessage(lHwnd,WM_COMMAND,MIN_ALL_UNDO,0);
    return 0;
}

How can I access the FindWindow and SendMessage API function and the HWND type in C#.net?

Answer

Stanislav Kniazev picture Stanislav Kniazev · Apr 24, 2009

PInvoke.net is your friend :-)

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1 {
class Program {
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]
    static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);

    const int WM_COMMAND = 0x111;
    const int MIN_ALL = 419;
    const int MIN_ALL_UNDO = 416;

    static void Main(string[] args) {
        IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);
        SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero); 
        System.Threading.Thread.Sleep(2000);
        SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero);
    }
}
}