日期:2014-05-18  浏览次数:20783 次

实现单实例的问题? 急急!!!!
loginForm frm = new loginForm();

  //保证单实例运行
  bool newMutexCreated = false;

  string mutexName = "Local\\" +
  System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

  Mutex mutex = null;
  try
  {
  // Create a new mutex object with a unique name
  mutex = new Mutex(false , mutexName, out newMutexCreated);
  }
  catch (Exception ex)
  {
  //MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace +
  // "\n\n" + "Application Exiting...", "Exception thrown");
  Application.Exit();
  }

  // When the mutex is created for the first time
  // we run the program since it is the first instance.

  if (newMutexCreated)
  {
  //判断是否打开主窗口
  if (DialogResult.OK == frm.ShowDialog())
  {
  Application.Run(new MsnManage());
  }
  }
写了一个单实例程序,开始还可以实现,过一关时间不知道为什么不好用拉,有没有高手指点一下迷津



------解决方案--------------------
用下面的代码可以支持单例

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace SingleInstance
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//这里需要更改你的程序的Process名称
if (!IsExist("SingleInstance"))
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("Exist one Instance");
Application.Exit();
}
}

private static bool IsExist(string name)
{
//获取系统进程
Process[] prces = Process.GetProcesses();
int count = 0;
foreach (Process pro in prces)
{
if(pro.ProcessName==name)
{
count++;
}
}
if(count>1)
return true;
else
return false;
}

}
}
------解决方案--------------------
using System.Diagnostics; //用于使程序只运行一次
using System.Reflection; //用于使程序只运行一次
using System.Runtime.InteropServices; //用于使程序只运行一次
using System.IO;//用于使程序只运行一次

[STAThread]
static void Main() 
{
//用于使程序只运行一次
Process instance=RunningInstance();
if( instance!= null )
{
// MessageBox.Show( "程序已在运行!" );
//确保窗口没有被最小化或最大化 
ShowWindowAsync(instance.MainWindowHandle , 1); 
//设置真实例程为foreground window 
SetForegroundWindow (instance.MainWindowHandle); 
return;
}
.........
........


/// <summary>
/// 确保窗口没有被最小化或最大化 (用于使程序只运行一次)
/// </summary>
/// <param name="hWnd">进程中主窗口的窗口句柄</param>
/// <param name="cmdShow">1还原窗口,2 窗口最小化,3 窗口最大化</param>
///