/// <summary>
/// Get window handle function
/// </summary>
/// <param name="lpClassName">window class name</param>
/// <param name="lpWindowName" >Window title name</param>
/// <returns>Return handle</returns>
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hWndParent, CallBack lpfn, int lParam);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hwnd, StringBuilder sb, int length);
public delegate bool CallBack(IntPtr hwnd, int lParam);
/// <summary>
/// Find the control handle on the form
/// </summary>
/// <param name="hwnd">parent form handle</param>
/// <param name="lpszWindow ">Control title (Text)</param>
/// <param name="bChild">Set whether to search in the child form</param>
/// <returns>Control handle, if not found, return IntPtr.Zero </returns>
public static IntPtr FindWindowExMy(IntPtr hwnd, string lpszWindow, bool bChild)
{ IntPtr iResult = IntPtr.Zero; // First find controls on the parent form iResult = FindWindowEx(hwnd, 0, null, lpszWindow); / / If found, directly return the control handle if (iResult != IntPtr.Zero) return iResult;
// If it is set not to search in the child form
if (!bChild)
return iResult;
// Enumerate child windows, find control handles
int i = EnumChildWindows(
hwnd,
(h, l) =>
{ IntPtr f1 = FindWindowEx(h, 0, null, lpszWindow); if (f1 == IntPtr.Zero) return true; else { StringBuilder title = new StringBuilder(200); int len; len = GetWindowText(hwnd, title, 200);
iResult = f1;
return false;
}
},
0);
// return search result
return iResult;
}