c#防止同一个帐号在同一台电脑上重复登录(内存锁定)

 

bool flag = MemoryMappedFileHelper.CheckActive(tbUser.text);

if (!flag)
{
System.Windows.Forms.MessageBox.Show("该账户已经登录过啦", "提示框");
BaseEnvDQ.ForceQuit();
return;
}

public class MemoryMappedFileHelper
{
//不能写到函数内容,防止GC回收
static MemoryMappedFile HeadMMF = null;
/// <summary>
/// 检查判断系统是否可以被激活
/// </summary>
/// <param name="AppName"></param>
/// <returns></returns>
public static bool CheckActive(string AppName)
{
bool Active = false;
int HeadMMF_Size = Marshal.SizeOf<bool>();

try
{
HeadMMF = MemoryMappedFile.CreateOrOpen($"mmf_ann_{AppName}_active", HeadMMF_Size, MemoryMappedFileAccess.ReadWrite);
using (var accessor = HeadMMF.CreateViewAccessor(0, HeadMMF_Size, MemoryMappedFileAccess.ReadWrite))
{
int size = Marshal.SizeOf<bool>();
bool used = false;
accessor.Read(0, out used);
if (used)
{
Active = false;
HeadMMF?.Dispose();
HeadMMF = null;
}
else
{
accessor.Write(0, true);
Active = true;
}
}
}
catch (Exception ex)
{
Active = false;

}
return Active;
}

}

posted @ 2022-02-24 15:22  普天2022  阅读(229)  评论(0编辑  收藏  举报