Threading Mutex と user32.dll を使用できます
これを試して
ステップ 1 : 次の定数を宣言します。
private const int SW_NORMAL = 1; // see WinUser.h for definitions
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_RESTORE = 9;
[DllImport("User32", EntryPoint = "FindWindow")]
static extern IntPtr FindWindow(string className, string windowName);
[DllImport("User32", EntryPoint = "SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32", EntryPoint = "SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32", EntryPoint = "SetWindowPlacement")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("User32", EntryPoint = "GetWindowPlacement")]
private static extern bool GetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
}
ステップ 2: このメソッドを追加します。
public void application_run(Form form1)
{
bool createdNew;
System.Threading.Mutex m = new System.Threading.Mutex(true, form1.Name, out createdNew);
if (!createdNew)
{
MessageBox.Show("...", "...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);//Alert message
try
{
// see if we can find the other app and Bring it to front
IntPtr hWnd = FindWindow(null, form1.Text);
if (hWnd != IntPtr.Zero)
{
LoaderDomain.WINDOWPLACEMENT placement = new LoaderDomain.WINDOWPLACEMENT();
placement.length = Marshal.SizeOf(placement);
GetWindowPlacement(hWnd, ref placement);
placement.showCmd = SW_SHOWMAXIMIZED;
SetWindowPlacement(hWnd, ref placement);
SetForegroundWindow(hWnd);
}
}
catch
{
//rien
}
}
else
{
Application.Run(form1);
}
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}
ステップ 3 : メインで交換する
Application.run(forms);
前のメソッドへの呼び出しによって