// Program.cs created with MonoDevelop
//
// Copyright (C) 2021 Hiperscan GmbH Dresden, Germany
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License version 3
// as published by the Free Software Foundation.
//
// 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.
// See the GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program; if not, see http://www.gnu.org/licenses or write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA, 02110-1301 USA
//




using System;

namespace ShowApoIdent
{
    class MainClass
    {
        const int SW_NORMAL = 1;

        [System.Runtime.InteropServices.DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr handle);
        [System.Runtime.InteropServices.DllImport("User32.dll")]
        private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
        [System.Runtime.InteropServices.DllImport("User32.dll")]
        private static extern bool IsIconic(IntPtr handle);

        public static void Main(string[] args)
        {
            try
            {
                System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("QuickStep");

                DateTime date = DateTime.MaxValue;
                System.Diagnostics.Process winner = null;

                foreach (System.Diagnostics.Process process in processes)
                {
                    if (process.StartTime < date)
                    {
                        date = process.StartTime;
                        winner = process;
                    }
                }

                IntPtr handle = winner.MainWindowHandle;
                if (IsIconic(handle))
                {
                    ShowWindow(handle, 1);
                }

                SetForegroundWindow(handle);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while execution: {0}", ex);
            }
        }
    }
}
