这个Run 函数是创建一个带有应用程序名的Mutex,也顺便检查返回的错误代码,去看是否这个mutex已经存在;如果不错在呢,就让这个应用程序运行;
最终会把这个Mutex释放掉;这样的写法是不是很简单,呵呵..
如何引用这个类呢?下面是主程序的入口..
‘首先定义这个类 这是必须地。
Private oOneInstance As SingleInstanceApplication = Nothing
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘实例话这个类,这也是必须地.
oOneInstance = New SingleInstanceApplication()
‘ 调用这个类下面的主函数Run,这更是必须地.
oOneInstance.Run(Me)
End Sub
Private oOneInstance As SingleInstanceApplication = Nothing
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘实例话这个类,这也是必须地.
oOneInstance = New SingleInstanceApplication()
‘ 调用这个类下面的主函数Run,这更是必须地.
oOneInstance.Run(Me)
End Sub
上述代码全是关于VB.NET写的,有没有用C#写的呢,下面就是啦.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Bitmatic
{
static class SingleInstanceApplication
{
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr CreateMutex(IntPtr Attr, bool Own, string Name);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool ReleaseMutex(IntPtr hMutex);
const long ERROR_ALREADY_EXISTS = 183;
public static void Run(Form frm)
{
string name = Assembly.GetExecutingAssembly().GetName().Name;
IntPtr mutexHandle = CreateMutex(IntPtr.Zero, true, name);
long error = Marshal.GetLastWin32Error();
if (error != ERROR_ALREADY_EXISTS)
Application.Run(frm);
ReleaseMutex(mutexHandle);
}
}
}
[MTAThread]
static void Main()
{
SingleInstanceApplication.Run(new Form1());
}
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Bitmatic
{
static class SingleInstanceApplication
{
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr CreateMutex(IntPtr Attr, bool Own, string Name);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool ReleaseMutex(IntPtr hMutex);
const long ERROR_ALREADY_EXISTS = 183;
public static void Run(Form frm)
{
string name = Assembly.GetExecutingAssembly().GetName().Name;
IntPtr mutexHandle = CreateMutex(IntPtr.Zero, true, name);
long error = Marshal.GetLastWin32Error();
if (error != ERROR_ALREADY_EXISTS)
Application.Run(frm);
ReleaseMutex(mutexHandle);
}
}
}
[MTAThread]
static void Main()
{
SingleInstanceApplication.Run(new Form1());
}
上述代码在Windows CE(PDA),Windows XP下调试;开发工具是Visual Studio.Net 2008;
最后是感言,非常感谢这么多的网友奉献他们的智慧,让我写这篇文章;更重要的是我在搜索的过程中,没有一篇完整的文章对在.NET Framework 和.NET Compact Framework对这个议题进行探讨;又近阶段有个项目要实现这样的用户需求,故总结归纳之,希大家共勉!