Skip to content

Commit

Permalink
[startup] make programe can only run one reality
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinZonda committed Jun 7, 2020
1 parent d230147 commit a8261b3
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion NaiveSharp/Program.cs
@@ -1,4 +1,7 @@
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace NaiveSharp
Expand All @@ -10,7 +13,46 @@ static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainWindow());
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new MainWindow());
}
else
{
MessageBox.Show("Naive# has been running.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
HandleRunningInstance(instance);
}
}

public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
return process;
}
}
}
return null;
}

public static void HandleRunningInstance(Process instance)
{
ShowWindow(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
}

[DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
}
}

0 comments on commit a8261b3

Please sign in to comment.