同じソフトを複数起動されては困る、または意味のないときに、プログラムの2重起動防止するのはよいのですが、既に起動済みのプログラムが裏に隠れてしまっていて、気が付かないときがよくあります。
今回は、2重起動防止と既起動プログラムの全面化を同時におこなうコードを残しておきます。
手順
App.XamlにStartupを追加し、イベントプロシージャをApp.xaml.csに作ります。
最近のVSではApp.XamlにStartupを追加すると、自動でApp.xaml.csに作成してくれるので、簡単です。
サンプルコード
App.Xaml
<Application x:Class="HogeHoge.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Register4Start"
             StartupUri="MainWindow.xaml"
             Startup="Application_Startup"/>
    <Application.Resources>
         
    </Application.Resources>
</Application>
App.xaml.cs
using System;
using System.Windows;
using System.Diagnostics;
namespace HogeHoge
{
	/// <summary>
	/// App.xaml の相互作用ロジック
	/// </summary>
	public partial class App : Application
	{
		/// WinAPIを直接呼び出すための宣言
		[System.Runtime.InteropServices.DllImport("User32.dll")]
		private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
		[System.Runtime.InteropServices.DllImport("User32.dll")]
		private static extern bool SetForegroundWindow(IntPtr hWnd);
		private const int SW_SHOWNORMAL = 1;
		private void Application_Startup(object sender, StartupEventArgs e)
		{
			Process currentProcess = Process.GetCurrentProcess();							// 現在のプロセスの取得
			Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);	// 自分のプロセスと同じ名前のプロセスを取得
			foreach(Process p in processes)
			{
				if(p.Id != currentProcess.Id)	// 同じ名前のプロセスが存在するとき
				{
					// 既に起動しているウィンドウを前面に表示する
					ShowWindow(p.MainWindowHandle, SW_SHOWNORMAL);
					SetForegroundWindow(p.MainWindowHandle);
					/* 起動を中止してプログラムを終了 */
					this.Shutdown();
				}
			}
		}
	}
}
 
  
  
  
  