using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
//using System.Runtime.InteropServices;
using System.Diagnostics;

namespace GuiEdit
{
    /// <summary>
    /// App.xaml の相互作用ロジック
    /// </summary>
    public partial class App : Application
    {
        private static System.Threading.Mutex mutex;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            mutex = new System.Threading.Mutex(false, "NodokaGUIEdit");

            if (!mutex.WaitOne(0, false))
            {
                //MessageBox.Show("running");

                mutex.Close();
                mutex = null;

                int SW_NORMAL = 1;
                
                Process hThisProcess = Process.GetCurrentProcess();
                Process[] hProcesses = Process.GetProcessesByName(hThisProcess.ProcessName);
                int iThisProcessId   = hThisProcess.Id;

                foreach (Process hProcess in hProcesses)
                {
                    if (hProcess.Id != iThisProcessId)
                    {
                        Win32API.ShowWindow(hProcess.MainWindowHandle, SW_NORMAL);
                        Win32API.SetForegroundWindow(hProcess.MainWindowHandle);
                    }
                }

                this.Shutdown();
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if (mutex != null)
            {
                mutex.ReleaseMutex();
                mutex.Close();
            }
        }
    }
}
