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
| using System.Runtime.InteropServices;
using System.Text;
public class WndSearcher
{
public static IntPtr SearchForWindow(string wndclass, string title)
{
SearchData sd = new SearchData { Wndclass=wndclass, Title=title };
EnumWindows(new EnumWindowsProc(EnumProc), ref sd);
return sd.hWnd;
}
public static bool EnumProc(IntPtr hWnd, ref SearchData data)
{
// Check classname and title
// This is different from FindWindow() in that the code below allows partial matches
StringBuilder sb = new StringBuilder(1024);
GetClassName(hWnd, sb, sb.Capacity);
if (sb.ToString().StartsWith(data.Wndclass))
{
sb = new StringBuilder(1024);
GetWindowText(hWnd, sb, sb.Capacity);
if (sb.ToString().StartsWith(data.Title))
{
data.hWnd = hWnd;
return false; // Found the wnd, halt enumeration
}
}
return true;
}
public class SearchData
{
// You can put any dicks or Doms in here...
public string Wndclass;
public string Title;
public IntPtr hWnd;
}
private delegate bool EnumWindowsProc(IntPtr hWnd, ref SearchData data);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, ref SearchData data);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
}
//Then you'd call:
// If you're viewing this page with IE, this *should* return the hwnd of the browser
IntPtr hWnd = WndSearcher.SearchForWindow("IEFrame", "pinvoke.net: EnumWindows"); |
Partager