Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SendMessage() to minimize all windows, but need a more efficient way than Thread.Sleep() to wait until the legacy desktop is showing

Tags:

c#

In my C# console application, I am using SendMessage() to minimize all windows, effectively showing the Windows 8 Legacy Desktop. This works great, but I have to use a Thread.Sleep(1000) in order to wait for the Legacy Desktop to actually show before before I try to do anything else.

IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero);
Thread.Sleep(1000);

I really want to replace the Thread.Sleep() with a more efficient way to detect that the Legacy Desktop is showing before continuing on.

Any ideas?

Edit: Here are the Interop wrappers and constants. just in case it helps..

[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;
like image 572
user1190320 Avatar asked May 27 '13 10:05

user1190320


1 Answers

I'm not sure if this will work any better for you, but perhaps it's worth a try...

(1) Add to your project a reference to "Shell32" (via Add Reference -> COM -> Microsoft Shell Controls and Automation).

(2) Set the reference's "Embed Interop Types" to false.

(3) Use the following code to minimise all the windows:

dynamic shell = new Shell32.ShellClass();
shell.MinimizeAll();

However, I suspect that this is just an alternative way of doing the SendMessage().

like image 66
Matthew Watson Avatar answered Nov 10 '22 15:11

Matthew Watson