//------------------------------------------------------------------------------
/// <copyright from='2004' to='2005' company='Christian Forsberg'>
///		Copyright (c) Christian Forsberg, chris@businessanyplace.net.
///
///   This program is distributed in the hope that it will be useful,
///   but WITHOUT ANY WARRANTY; without even the implied warranty of
///   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;

namespace TaskManager
{
	/// <summary>
	/// This is the Window helper class.
	/// </summary>
	public class WindowHelper
	{
		public static Window[] EnumerateTopWindows()
		{
			ArrayList windowList = new ArrayList();
			IntPtr hWnd = IntPtr.Zero;
			Window window = null;
			
			// Получим первое окно
			hWnd = GetActiveWindow();
			hWnd = GetWindow(hWnd, GW_HWNDFIRST);
			
			while(hWnd != IntPtr.Zero)
			{
        if(IsWindow(hWnd) && IsWindowVisible(hWnd))
        {
          IntPtr parentWin = GetParent(hWnd);
          if ((parentWin == IntPtr.Zero))
          {
            int length = GetWindowTextLength(hWnd);
            if (length > 0)
            {
              string s = new string('\0', length + 1);
              GetWindowText(hWnd, s, length + 1);
              s = s.Substring(0, s.IndexOf('\0'));
              if(s != "Tray" && s != "Start" && s != "Диспетчер задач")
              {
                window = new Window();
                window.Handle = hWnd;
                window.Text = s;
                windowList.Add(window);
              }
            }
          }
        }
				hWnd = GetWindow(hWnd, GW_HWNDNEXT);
			}
			return (Window[])windowList.ToArray(typeof(Window));
		}

    public static void ActivateWindow(IntPtr hWnd)
    {
        // Активируем приложение
        SetForegroundWindow(hWnd);
    }

    public static void CloseWindow(IntPtr hWnd)
    {
        // Закрываем приложение
        SendMessage(hWnd, WM_CLOSE, 0, 0);
    }

    public static void CloseApps()
    {
        // Закрываем все приложения
        SHCloseApps(int.MaxValue);
    }

    #region API declarations
    private const uint GW_HWNDFIRST = 0; 
    private const uint GW_HWNDLAST = 1; 
    private const uint GW_HWNDNEXT = 2; 
    private const uint GW_HWNDPREV = 3; 
    private const uint GW_OWNER = 4; 
    private const uint GW_CHILD = 5; 
    private const uint WM_CLOSE = 0x10;

    [DllImport("coredll.dll")]
    private extern static bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("coredll.dll")]
    private static extern int SendMessage(IntPtr hWnd, uint wMsg, int wParam, int lParam);

    [DllImport("aygshell.dll")]
    private static extern int SHCloseApps(int dwMemSought);

    [DllImport("coredll.dll")]
    private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

    [DllImport("coredll.dll")]
    private static extern int GetClassName(IntPtr hWnd, string lpClassName, int nMaxCount);

    [DllImport("coredll.dll")]
    private static extern int GetWindowText(IntPtr hWnd, string lpString, int nMaxCount);

    [DllImport("coredll.dll", CharSet=CharSet.Auto)]
    private static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("coredll.dll")]
    private static extern IntPtr GetParent(IntPtr hWnd);

    [DllImport("coredll.dll")]
    private static extern int GetWindowLong(IntPtr hWnd, int cmd);

    [DllImport("coredll.dll")]
    private static extern IntPtr GetActiveWindow();

    [DllImport("coredll.dll")]
    private static extern bool IsWindow(IntPtr hWnd);

    [DllImport("coredll.dll")]
    private static extern bool IsWindowVisible(IntPtr hWnd);
    #endregion
	}

	public class Window
	{
		private IntPtr handle;
    public IntPtr Handle
    { get { return handle; } set { handle = value; } }

    private string text;
    public string Text
    { get { return text; } set { text = value; } }

		public override string ToString()
		{
			return text;
		}
	}
}
