Windows標準のフォトビューワーのように、ファイルがソートされている順序をそのまま取得したい場合があるかもしれません。その場合の方法は、ここにありました。
How to get Files/folders Sort order in Windows Explorer window in C#?
Visual Studio 2015 / Windows 10 を例に解説します。
必要なアセンブリへの参照を追加する必要があるため、プロジェクトの「参照を追加」から、Microsoft Shell Controls and Automation を追加してください。
参考:How to use Shell32 within a C# application? – Stack Overflow
加えて、C:\Windows\System32\shdocvw.dll (64ビットOSの場合) への参照も追加してください。右下の参照(B)...をクリックすると追加できます。
そうしたら、次のようなコードで出来ます。(ほぼコピペ)
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
// Shell32クラスは Interop.Shell32 アセンブリにあり、
// COMのMicrosoft Shell Controls and Automationから追加できます
var shell = new Shell();
// ShellWindows クラスは C:\Windows\System32\shdocvw.dll にあります
var shellWindows = (ShellWindows)shell.Windows();
foreach (ShellBrowserWindow shellWindow in shellWindows)
{
var s = shellWindow.LocationURL;
// このオブジェクトはExplorerウィンドウ情報を保持しています
var view = (ShellFolderView)shellWindow.Document;
textBox1.Text += "app : " + view.Folder.Title + "\r\n";
textBox1.Text += "focus : " + view.FocusedItem.Name + "\r\n";
textBox1.Text += "sort order : " + view.SortColumns + "\r\n";
textBox1.Text += "\r\n";
}
}
Visual Studio 2010 以降では、クラス名が ShellClass ではなく Shell に変わったようです。
参考:ShellClass shell = new ShellClass();がコンパイルエラーになるので調べてみた
エクスプローラーが開いているフォルダのパスを取得するのが難しいのはまた別の話っぽい。
