c# 控制职能运行单一实例,再次运行显示已经运行的实例

时间:2021-07-18 11:44:22

有这么个需求,软件只能运行一个实例,软件运行后可以让其隐藏运行

再次运行这个软件的时候就让正在运行的实例显示出来

=================================

当软件隐藏后没办法拿到句柄

于是只有第一次运行的时候讲句柄保存下来,于是有了下面的

  private void HideForm()
{
string handlestr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToInt32().ToString();
string path = Application.StartupPath + "\\Handle";
if (!File.Exists(path))
{
File.Create(path).Close();
}
using (StreamWriter writer = new StreamWriter(path, false))
{
writer.Write(handlestr);
}
this.Hide();
}

哪里需要隐藏就调用

下面是控制

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO; namespace NIKE.Client
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//StaticPass.cf = new ClientForm();
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new FormMain());
bool ret;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
if (ret)
{
System.Windows.Forms.Application.EnableVisualStyles(); //这两行实现 XP 可视风格
//System.Windows.Forms.Application.DoEvents(); //这两行实现 XP 可视风格
Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new FormMain());
// Main 为你程序的主窗体,如果是控制台程序不用这句
mutex.ReleaseMutex();
}
else
{ string path = Application.StartupPath + "\\Handle";
int handle = ;
using (StreamReader reader = new StreamReader(path))
{
handle = int.Parse(reader.ReadToEnd());
}
IntPtr i = new IntPtr(handle);
bool isok = ShowWindow(i, );
SetForegroundWindow(i);
// SetForegroundWindow(hWnd);
// MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n本次打开无效", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
// 提示信息,可以删除。
Application.Exit();//退出程序
}
} [DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOWNORMAL = ; }
}