using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// 以下の名前空間をインポートする
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ProcessShowPrevProcess
{
public partial class Form1 : Form
{
public class MyProcess
{
[DllImport("USER32.DLL", CharSet = CharSet.Auto)]
private static extern int ShowWindow(
System.IntPtr hWnd,
int nCmdShow
);
[DllImport("USER32.DLL", CharSet = CharSet.Auto)]
private static extern bool SetForegroundWindow(
System.IntPtr hWnd
);
private const int SW_NORMAL = 1;
/// ------------------------------------------------------------------------------------
///
/// 同名のプロセスが起動中の場合、メイン ウィンドウをアクティブにします。
///
/// 既に起動中であれば true。それ以外は false。
/// ------------------------------------------------------------------------------------
public static bool ShowPrevProcess()
{
Process hThisProcess = Process.GetCurrentProcess();
Process[] hProcesses = Process.GetProcessesByName(hThisProcess.ProcessName);
int iThisProcessId = hThisProcess.Id;
foreach (Process hProcess in hProcesses)
{
if (hProcess.Id != iThisProcessId)
{
ShowWindow(hProcess.MainWindowHandle, SW_NORMAL);
SetForegroundWindow(hProcess.MainWindowHandle);
return true;
}
}
return false;
}
}
[System.STAThread()]
private static void Main()
{
// 同名のプロセスが起動していない時は起動する
if (!MyProcess.ShowPrevProcess())
{
Application.Run(new Form1());
}
}
}
}