WINFORM 应用程序唯一执行验证

通过应用程序名称创建Mutex实现跨程序标识.
program中的调用方法:
SingleProcessFixer singleProcessFixer = new SingleProcessFixer();
if (!singleProcessFixer.CreateMutex()) //程序正在运行.
 
public class SingleProcessFixer 
{
    /// <summary>
    /// core mutex
    /// </summary>
    Mutex mutex = null;
 
    /// <summary>
    /// Create mutex in currect assembly and return if create successful.
    /// </summary>
    /// <returns>if create successful</returns>
    public bool CreateMutex()
    {
        return CreateMutex(Assembly.GetEntryAssembly().FullName);
    }
 
    /// <summary>
    /// Create mutex by name and return if create successful.
    /// </summary>
    /// <param name="name">name for mutex</param>
    /// <returns>if create successful.</returns>
    public bool CreateMutex(string name)
    {
        bool result = false;
        mutex = new Mutex(true, name, out result);
        return result;
    }
 
    /// <summary>
    /// Release mutex.
    /// </summary>
    public void ReleaseMutex()
    {
        if (mutex != null)
        {
            mutex.Close();
        }
    }
}

posted @ 2017-08-25 11:50  sunlyk  阅读(284)  评论(0编辑  收藏  举报