using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace TST.SINGLE
{
publicclass TSTPGM
{
///<summary>
/// The main entry point for the application.
///</summary>
[STAThread]
staticvoid Main()
{
bool createdNew =true;
using (Mutex mutex =new Mutex(true, "MyApplicationName", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
IntPtr hWnd = process.MainWindowHandle;
ShowWindowAsync(hWnd, WS_SHOWNORMAL); //调用api函数,正常显示窗口
SetForegroundWindow(hWnd);//将窗口放置最前端。 break;
}
}
}
}
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
}
}
C#实现只许一个实例运行
最新推荐文章于 2024-09-09 17:03:46 发布