How do I arrange or sort the desktop icons in c#?

2019-07-20 02:45发布

问题:

You know when you right-click the desktop and there's a "Sort by" option that allows you to sort the icons by "Name", "Size", "Item Type", or "Date Modified"? Well, I want to find a way to sort the desktop's icons with a push of a button.

I saw a similar question being asked here on stackoverflow but it's old and the code didn't work for me. The link to the question is: Arranging desktop icons with C# . I'm trying to achieve this in Windows 10.

There was a comment on there that said that the LVM_* and LVA_* values are stored in the commctrl.h file which comes with the SDK. I couldn't find that file for some reason.

Here's what i'm using:

  //sort desktop
     public const int LVM_ARRANGE = 4118;
     public const int LVM_ALIGNLEFT = 1;


     [DllImport("user32.dll", CharSet = CharSet.Auto)]
     public static extern IntPtr GetDesktopWindow(); 


    [DllImport("user32.dll")]
     public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

     //end of sort desktop 

private void organizeBtn_Click(object sender, EventArgs e)
   {
       var DesktopHandle = GetDesktopWindow();
       MessageBox.Show(GetDesktopWindow().ToString());

       SendMessage(GetDesktopWindow(), LVM_ARRANGE, LVM_ALIGNLEFT, 0);

   }

I've been digging for info or some sort of direction about this topic, especially regarding windows 10, but I can't find much. Please help?

回答1:

In Windows 10, the desktop (not tile world!) is still a SysListView32, but the GetDesktopWindow API call will return the handle of its grandparent, a Progman window - reminiscence of the ancient "Program Manager" of Windows 3.0. Then there is a shim of the SHELLDLL_DefView class, and below that you find buried the listview you're after.

Use the information from this answer to move down from the shell window to the folder view, which you can eventually send the LVM_ARRANGE message.

This is a brittle approach, as it relies on undocumented properties of the operating system, which may change at any time with updates or new versions. It will probably break also when a user uses a slideshow as desktop background, because Windows then rearranges the desktop window stack. Hack to deal with this here.

Another approach which is documented and less likely to break in future versions, with the downside of involving COM and a nightmare from C#, is via the IFolderView of shell automation, two relevant finds here and here.