Let me elaborate. By "items" I mean all the items you see one the desktop (Windows) which includes "My Computer", "Recycle Bin", all the shortcuts etc. If I select all the items on the desktop I get the count in the properties displayed. It is this count I want, programmatically.
The problem I face:
The desktop as we see has items from my account, also the All Users
's desktop items and also other shortcuts like "My Computer", "Recycle Bin". In total, 3 things. So I can't just get the item count from the physical path to Desktop directory. So this fails:
int count =
Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder
.DesktopDirectory)
).Length;
I know SpecialFolder.Desktop
stands for the logical desktop as we see. But this fails again since GetFolderPath()
again gets the physical path of user's desktop:
int count =
Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder
.Desktop)
).Length;
What is the right way to get total count on the user's desktop?
I'm answering for myself the answer I finally found out with the help of tips and links posted here.
private const uint GET_ITEM_COUNT = 0x1000 + 4;
[DllImport("user32.DLL")]
private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.DLL")]
private static extern IntPtr FindWindow(string lpszClass, string lpszWindow);
[DllImport("user32.DLL")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
public static int GetDesktopCount()
{
//Get the handle of the desktop listview
IntPtr vHandle = FindWindow("Progman", "Program Manager");
vHandle = FindWindowEx(vHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
vHandle = FindWindowEx(vHandle, IntPtr.Zero, "SysListView32", "FolderView");
//Get total count of the icons on the desktop
int vItemCount = SendMessage(vHandle, GET_ITEM_COUNT, 0, 0);
return vItemCount;
}
There's an interesting (rather annoying!) thing I came to learn meanwhile. The desktop you see on your screen is different from the desktop's folder view. Even if you uncheck My Computer and MyDocument from being on desktop (the desktop you see on monitor), these icons can be still there in the folder view of the desktop. I tried the solution given in this link, but it gives the count of items present in the folder view. The solution I posted above would yield the perfect result I want. The solution was got from here, by Zhi-Xin Ye. Thanks @C.Evenhuis for the tip.