1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public class ShellMethods
{
[DllImport("user32", SetLastError = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32", SetLastError = true)]
private static extern int SendMessage(IntPtr hwnd, int msg, int pid_info, int extra_info);
[DllImport("user32", SetLastError = true)]
private static extern bool IsWindowVisible(IntPtr whnd);
[DllImport("user32", SetLastError = true)]
private static extern int GetClassName(IntPtr hwnd, StringBuilder buffer, int bufferSize);
[DllImport("kernel32", SetLastError = true)]
private static extern int GetCurrentProcessId();
//Signature des méthodes de Shell32 (non-signée)
[DllImport("Shell32", SetLastError = true)]
private static extern IntPtr SHLockShared(int hMem, int pid);
[DllImport("Shell32", SetLastError = true)]
private static extern void SHUnlockShared(IntPtr pv);
[DllImport("Shell32", SetLastError = true)]
private static extern void SHFreeShared(int hMem, int pid);
[DllImport("Shell32", SetLastError = true)]
private static extern int ILClone(IntPtr pv);
[DllImport("Shell32", SetLastError = true)]
private static extern bool SHGetPathFromIDList(int result, StringBuilder buffer);
private const int VM_USER = 0x400;
private const int CWM_GETPATH = VM_USER + 12;
private const int MAX_PATH = 255;
private StringBuilder pathBuffer = new StringBuilder(MAX_PATH);
private StringBuilder windowTypeBuffer = new StringBuilder(MAX_PATH);
public String ShellGetPath(IntPtr hwnd)
{
int result = 0;
//On récupère le pid
int pid = GetCurrentProcessId();
//On récupère l'adresse de début de la zone mémoire
int hMem = SendMessage(hwnd, CWM_GETPATH, pid, 0);
if (hMem != 0)
{
//On lit la mémoire partagée
IntPtr pv = SHLockShared(hMem, pid);
if (pv != null)
{
//On copie
result = ILClone(pv);
SHUnlockShared(pv);
}
//On libère la mémoire partagée
SHFreeShared(hMem, pid);
}
//On récupère le chemin du pid (du shell)
SHGetPathFromIDList(result, pathBuffer);
return pathBuffer.ToString() ;
}
/// <summary>
/// Retourne la fenêtre active (qui a lefocus)
/// </summary>
/// <returns>Le handle de la fenêtre active</returns>
public IntPtr GetActiveWindow()
{
return GetForegroundWindow();
}
/// <summary>
/// Détermine si la fenêtre est un shell
/// </summary>
/// <param name="hwnd">le handle de la fenêtre</param>
/// <returns>Vrai si la fenêtre est un shell</returns>
public Boolean ActiveWindowIsShell(IntPtr hwnd)
{
//On récupère le type de la fenêtre
GetClassName(hwnd, windowTypeBuffer, MAX_PATH);
//Elle doit être visible et de type shell (fenêtre explorer ou structure arborescente)
if (IsWindowVisible(hwnd) && (windowTypeBuffer.ToString() == "ExploreWClass" || windowTypeBuffer.ToString() == "CabinetWClass"))
{
return true;
}
else
{
return false;
}
}
} |
Partager