声明:GetProName.h
#ifndef _GETPRONAME_H_
#define _GETPRONAME_H_
namespace SpaceGetProcessName
{
char *GetProcesssName();
BOOL isProcess(char *pProName);
}
#endif
实现:GetProName.cpp
#include "stdafx.h"
#include "GetProName.h"
char *SpaceGetProcessName::GetProcesssName()
{
// 获取当前路径
TCHAR szPath[MAX_PATH];
if (!GetModuleFileName(NULL, szPath, MAX_PATH))
{
int err = GetLastError();
return NULL;
}
else
{
wstring wstrProName;
wstrProName = szPath;
wstrProName = wstrProName.substr(1,wstrProName.find_last_of(L"\\"));
//第一次调用确认转换后单字节字符串的长度,用于开辟空间
int pSize = WideCharToMultiByte(CP_OEMCP, 0, wstrProName.c_str(), wcslen(wstrProName.c_str()), NULL, 0, NULL, NULL);
char* pCStrProName = new char[pSize+1];
//第二次调用将双字节字符串转换成单字节字符串
WideCharToMultiByte(CP_OEMCP, 0, wstrProName.c_str(), wcslen(wstrProName.c_str()), pCStrProName, pSize, NULL, NULL);
// 更改字符串最后的 "\"
pCStrProName[pSize-1] = '\0';
// 更改后字符串的字符串 转为 wchar
int pSize1 = MultiByteToWideChar(CP_OEMCP, 0, pCStrProName, strlen(pCStrProName) + 1, NULL, 0);
wchar_t *pWCProName = new wchar_t[pSize1];
MultiByteToWideChar(CP_OEMCP, 0, pCStrProName, strlen(pCStrProName) + 1, pWCProName, pSize1);
wstring wstrVersionNext(pWCProName);
wstrVersionNext = wstrVersionNext.substr(1,wstrVersionNext.find_last_of(L"\\"));
int pSizeNext= WideCharToMultiByte(CP_OEMCP, 0, wstrVersionNext.c_str(), wcslen(wstrVersionNext.c_str()), NULL, 0, NULL, NULL);
char* pCStrProNext= new char[pSizeNext+1];
WideCharToMultiByte(CP_OEMCP, 0, wstrVersionNext.c_str(), wcslen(wstrVersionNext.c_str()), pCStrProNext, pSize, NULL, NULL);
pCStrProNext[pSizeNext] = '\0';
int len1 = strlen(pCStrProName);
int len2 = strlen(pCStrProNext);
char str[30] = {0};
for (int i = 1; i < len1-len2;i++)
{
str[i-1] = pCStrProName[i+len2];
}
delete pCStrProName;
delete pCStrProNext;
pCStrProName == NULL;
pCStrProNext == NULL;
return str;
}
}
BOOL SpaceGetProcessName::isProcess(char *pProName)
{
char *pGetPro = new char[10];
if (GetProcesssName() == NULL )
{
return FALSE;
}
strcpy(pGetPro,GetProcesssName());
if (!strcmp(pGetPro,pProName))
{
delete[] pGetPro;
pGetPro = NULL;
return FALSE;
}
else
{
delete[] pGetPro;
pGetPro = NULL;
return TRUE;
}
}