[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new mainFrm());
}
else
{
//MessageBox.Show("此程序已经启动!");
HandleRunningInstance(instance);
}
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
private 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;
}
private static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
}
博客展示了一段C#代码,用于检测程序是否已运行。通过`RunningInstance`方法获取当前进程,遍历进程列表判断是否有重复实例。若实例为`null`则正常运行程序,否则将已运行实例置于前台,还使用了`User32.dll`中的相关方法。
1619

被折叠的 条评论
为什么被折叠?



