I solve this by read all active windows
then check if this windows belongs to this process
if yes show it
you can see even windows titles to be sure the code work correctly
private static IntPtr GetActiveWindowHandle(IntPtr mainWindowHandle, int pId)
{
List<IntPtr> AllWindowsHandl = GetAllChildHandles(mainWindowHandle);
List<IntPtr> ActiveWindowsHandl = new List<IntPtr>();
List<string> ActiveWindowsName = new List<string>();
foreach (IntPtr i in AllWindowsHandl)
{
int proccessId = 0;
if (User32API.IsWindowVisible(i))
{
User32API.GetWindowThreadProcessId(i, out proccessId);
if (pId == proccessId)
{
ActiveWindowsHandl.Add(i);
StringBuilder title = new StringBuilder(256);
int x = User32API.GetWindowText(i, title, 256);
ActiveWindowsName.Add(title.ToString());
}
}
}
if (ActiveWindowsHandl.Count == 1) { return ActiveWindowsHandl[0]; }
return mainWindowHandle;
}
private static List<IntPtr> GetAllChildHandles(IntPtr mainWindowHandle)
{
List<IntPtr> childHandles = new List<IntPtr>();
GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(mainWindowHandle, childProc, pointerChildHandlesList);
}
finally
{
gcChildhandlesList.Free();
}
return childHandles;
}
private static bool EnumWindow(IntPtr hWnd, IntPtr lParam)
{
GCHandle gcChildhandlesList = GCHandle.FromIntPtr(lParam);
if (gcChildhandlesList == null || gcChildhandlesList.Target == null)
{
return false;
}
List<IntPtr> childHandles = gcChildhandlesList.Target as List<IntPtr>;
childHandles.Add(hWnd);
return true;
}
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int size);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);