最近作一個項目,有一個功能點須要獲取當前打開的文件夾,網上查資料+本身摸索,整理出以下代碼,鑑於網上完整的代碼比較少,顧貼出來,以供參考。若有更好的建議,歡迎留言。緩存
class Program
{
public delegate bool CallBack(int hwnd, int y);
//該函數枚舉全部屏幕上的頂層窗口,並將窗口句柄傳送給應用程序定義的回調函數。
//回調函數返回FALSE將中止枚舉,不然EnumWindows函數繼續到全部頂層窗口枚舉完爲止。
[DllImport("user32.dll")]
public static extern int EnumWindows(CallBack x, int y);
//該函數將指定窗口的標題條文本(若是存在)拷貝到一個緩存區內
[DllImport("user32.dll")]
public static extern int GetWindowText(int hwnd, StringBuilder lptrString, int nMaxCount);
//該函數得到一個指定子窗口的父窗口句柄
[DllImport("user32.dll")]
public static extern int GetParent(int hwnd);
//該函數得到給定窗口的可視狀態。
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(int hwnd);
//獲取窗體類名
[DllImport("User32.Dll ")]
public static extern void GetClassName(IntPtr hwnd, StringBuilder s, int nMaxCount);
//獲取窗體的子窗體句柄
[DllImport("User32.dll ")]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childe, string strclass, string FrmText);
///
/// 根據句柄獲取類名
///
///
///
private string GetFormClassName(IntPtr ptr)
{
StringBuilder nameBiulder = new StringBuilder(255);
GetClassName(ptr, nameBiulder, 255);
return nameBiulder.ToString();
}
///
/// 根據句柄獲取窗口標題
///
///
///
private string GetFormTitle(IntPtr ptr)
{
StringBuilder titleBiulder = new StringBuilder(255);
GetWindowText((int)ptr, titleBiulder, 255);
return titleBiulder.ToString();
}
public bool Report(int hwnd, int lParam)
{
int pHwnd = GetParent(hwnd);
//若是再沒有父窗口而且爲可視狀態的窗口,則遍歷
if (pHwnd == 0 && IsWindowVisible(hwnd) == true)
{
IntPtr cabinetWClassIntPtr = new IntPtr(hwnd);
string cabinetWClassName = GetFormClassName(cabinetWClassIntPtr);
//若是類名爲CabinetWClass ,則爲explorer窗口,能夠經過spy++查看窗口類型
if (cabinetWClassName.Equals("CabinetWClass", StringComparison.OrdinalIgnoreCase))
{
//下面爲一層層往下查找,直到找到資源管理器的地址窗體,經過他獲取窗體地址
IntPtr workerWIntPtr = FindWindowEx(cabinetWClassIntPtr, IntPtr.Zero, "WorkerW", null);
IntPtr reBarWindow32IntPtr = FindWindowEx(workerWIntPtr, IntPtr.Zero, "ReBarWindow32", null);
IntPtr addressBandRootIntPtr = FindWindowEx(reBarWindow32IntPtr, IntPtr.Zero, "Address Band Root", null);
IntPtr msctls_progress32IntPtr = FindWindowEx(addressBandRootIntPtr, IntPtr.Zero, "msctls_progress32", null);
IntPtr breadcrumbParentIntPtr = FindWindowEx(msctls_progress32IntPtr, IntPtr.Zero, "Breadcrumb Parent", null);
IntPtr toolbarWindow32IntPtr = FindWindowEx(breadcrumbParentIntPtr, IntPtr.Zero, "ToolbarWindow32", null);
string title = GetFormTitle(toolbarWindow32IntPtr);
Console.WriteLine(title);
int index = title.IndexOf(':');
index++;
string path = title.Substring(index, title.Length - index);
Console.WriteLine(path);
}
}
return true;
}
static void Main(string[] args)
{
EnumWindows(new Program().Report, 0);
Console.ReadKey();
}
}