如何在程序运行时保持程序不被打开 [英] How can I keep the program from being opened when it's already running
问题描述
我的程序偶尔出现问题,而exe的另一个副本正在后台运行。
I get issues occasionally with my programs running while another copy of the exe is running in the background.
我尝试在程序打开时进行检查,但它没有总是抓住另一个正在运行的副本
I tried putting in a check when the program opens but it doesn't always catch the other copy that's running
LONG findprogram()
{
LONG count;
DWORD aProcesses [1024],cbNeeded,cProcesses,processID,CurrentProcessId,lpExitCode;
unsigned int i;
TCHAR szProcessName [MAX_PATH] = TEXT("< unknown>");
HANDLE hProcess;
HMODULE hMod;
std :: string namepath =" programname.exe" ;;
std :: string cmpnamepath;
std :: wstring wtxt;
CurrentProcessId = GetCurrentProcessId();
$
if(!EnumProcesses(aProcesses,sizeof(aProcesses),& cbNeeded))
{
返回0;
}
cProcesses = cbNeeded / sizeof(DWORD);
计数= 1;&NBSP; //运行的进程数量
for(i = 0; i< cProcesses; i ++)
{
if(aProcesses [i]!= 0)
{
processID = aProcesses [i];
$
if(processID == CurrentProcessId) //省略当前节目
继续;
$
//获取流程的句柄。
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,processID);
$
//获取流程名称。
if(hProcess!= NULL)
{
if(EnumProcessModules(hProcess,& hMod,sizeof(hMod),& cbNeeded))
{
GetModuleBaseName(hProcess,hMod,szProcessName,sizeof(szProcessName)/ sizeof(TCHAR));
}
}
wtxt = szProcessName;
cmpnamepath = wstrtostr(wtxt);
$
if(ucase(cmpnamepath)== ucase(namepath))
{
count ++;
$
GetExitCodeProcess(hProcess,& lpExitCode);
TerminateProcess(hProcess,lpExitCode);
}
$
CloseHandle(hProcess);
}
}
返回计数;
}
$
LONG findprogram()
{
LONG count;
DWORD aProcesses[1024],cbNeeded,cProcesses,processID,CurrentProcessId,lpExitCode;
unsigned int i;
TCHAR szProcessName[MAX_PATH]=TEXT("<unknown>");
HANDLE hProcess;
HMODULE hMod;
std::string namepath="programname.exe";
std::string cmpnamepath;
std::wstring wtxt;
CurrentProcessId=GetCurrentProcessId();
if(!EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded))
{
return 0;
}
cProcesses=cbNeeded/sizeof(DWORD);
count=1; //number of processes running
for(i=0;i<cProcesses;i++)
{
if(aProcesses[i] != 0)
{
processID=aProcesses[i];
if(processID == CurrentProcessId) //leave out current program
continue;
// Get a handle to the process.
hProcess=OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,processID);
// Get the process name.
if(hProcess != NULL)
{
if(EnumProcessModules(hProcess,&hMod,sizeof(hMod),&cbNeeded))
{
GetModuleBaseName(hProcess,hMod,szProcessName,sizeof(szProcessName)/sizeof(TCHAR));
}
}
wtxt=szProcessName;
cmpnamepath=wstrtostr(wtxt);
if(ucase(cmpnamepath) == ucase(namepath))
{
count++;
GetExitCodeProcess(hProcess,&lpExitCode);
TerminateProcess(hProcess,lpExitCode);
}
CloseHandle(hProcess);
}
}
return count;
}
推荐答案
嗨
错误的论坛 - 这是一个VB.NET论坛,你的代码在行尾显示奇怪的半冒号:_
Wrong forum - this is a VB.NET forum and your code shows strange semi colons at end of lines :_
也许,尝试查看设置解决方案资源管理器 - >我的项目 - >申请 - >制作单一实例申请
这篇关于如何在程序运行时保持程序不被打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!