我有一个带有1个按钮的简单应用程序,可以知道Notepadd ++是否已经打开。我已经审查了一些主题,但我找不到合适的主题。在按钮方法里面我有:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
mutex = CreateMutex( NULL, TRUE, "Local\\$notepad++$");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
//MessageBox::Show(..[not open]..);
}
//MessageBox::Show(..[open]..);
}
};
我遇到“Local \ $ notepad ++ $”的问题,我收到了这个错误:
argument of type "const char *" is incompatible with parameter of type "LPCWSTR"
和另一个:
'HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES,BOOL,LPCWSTR)': cannot convert argument 3 from 'const char [18]' to 'LPCWSTR'
如果还有其他更简单的方法可以帮助我!我也尝试将名称更改为:notepad ++。我正在使用visual studio 2015 c ++
我已经过审核并作为参考使用:
C/C++ How to tell if a program is already running?
Is using a Mutex to prevent multiple instances of the same program from running safe?
答案 0 :(得分:0)
#include "Windows.h"
/*...*/
LPCSTR app_name = "Notepad++: a free (GNU) source code editor";
if (FindWindowA(0, app_name)) {
// it's open!
} else {
// it's not open!
}
对于您的方法,在引号
之前加上*CreateMutex( NULL, TRUE, *"Local\\$notepad++$");
答案 1 :(得分:0)
我有更好的解决方案:
int processExists(char *victim){
int res=0,ret;
PROCESSENTRY32 proc;
proc.dwSize=sizeof(proc);
HANDLE snap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(!snap){abort();}
for(ret=Process32First(snap,&proc);ret;ret=Process32Next(snap,&proc)){
if(strstr(proc.szExeFile,victim)){res=1;break;}
}
CloseHandle(snap);
return(res);
}
然后:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
mutex = CreateMutex( NULL, TRUE, "Local\\$notepad++$");
if (!processExists("notepad++.exe") {
//MessageBox::Show(..[not open]..);
}
//MessageBox::Show(..[open]..);
}
};