Jun 11, 2009

Howto get the TopMost Form in a WinForm App using Win32 API


public class Win32
{
public const int GW_HWNDNEXT = 2; // The next window is below the specified window
public const int GW_HWNDPREV = 3; // The previous window is above
public const int GW_HWNDFIRST = 0; // TopMost Windows
private const int SW_HIDE = 0;

[DllImport("user32", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);

[DllImport("user32.dll")]
static extern IntPtr GetTopWindow(IntPtr hWnd);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);

[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindow",SetLastError = true)]
public static extern IntPtr GetNextWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.U4)] int wFlag);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);


/// <summary>
/// Cautam Forma care este TopMost si o returnam.
/// Iteram doar prin ferestrele care sunt vizibile, incepand cu cel mai mare Z-order si continuand
/// cu cele care se ascund in spatele ei.
/// </summary>
/// <returns>Forma care este topmost in momentul apelarii functiei</returns>
public static Form GetTopMostWindow(IntPtr hWnd_mainFrm)
{
Form frm = null;

IntPtr hwnd = GetTopWindow((IntPtr)null);

//StringBuilder sb = new StringBuilder(256);
//GetWindowText(hwnd, sb, 256);
//Console.WriteLine("TOP WINDOW: " + sb.ToString());

if (hwnd != IntPtr.Zero)
{
while ((!IsWindowVisible(hwnd) || frm == null) && hwnd != hWnd_mainFrm)
{
// Get next above window if not visible
hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);

//GetWindowText(hwnd, sb, 256);
//Console.WriteLine(sb.ToString().Length == 0 ? "Fereastra fara nume" : sb.ToString());

try
{
frm = (Form)Form.FromHandle(hwnd);
}
catch
{
// Crapa daca incercam sa facem cast la un handle care nu e de tip Form
// In mod normal daca nu poate face cast returneaza null.
// Da la unele cast-uri crapa... pana mea!
}
}
}

return frm;
}
}

No comments:

Post a Comment