您的位置:首页 > 编程语言 > C#

C#实现只许一个实例运行

2012-04-10 08:45 351 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: