CUtilFunc.cpp

来源:互联网 发布:office软件验收 编辑:程序博客网 时间:2024/07/24 01:13

// UtilityFunc.cpp: implementation of the CUtilityFunc class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "UtilFunc.h"
#include <afxsock.h>
#include <tlhelp32.h>
#include <list>
#include <algorithm>
#include <ImageHlp.h>
#include "VfxClasses\VFXVersionInfo.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
 
CUtilFunc::CUtilFunc()
{

}

CUtilFunc::~CUtilFunc()
{

}
BOOL CUtilFunc::GetHostInfo(char * outIP, char * outName)
{
 char   name[300];
 if (gethostname(name, 300) == 0)
 {
  if (outName)
  {
   strcpy(outName, name);
  }

  PHOSTENT  hostinfo;
  if ((hostinfo = gethostbyname(name)) != NULL)
  {
   LPCSTR pIP = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
   strcpy(outIP, pIP);
   return TRUE;
  }
 }
 return FALSE;
}
void CUtilFunc::GetHostIp(char *svrIp)
{
 
 if (!AfxSocketInit())
  return ;
 
 char  HostName[128];
 memset(HostName,'\0',128);
    CString StrIP; 
 //获得主机名
 if( gethostname(HostName, 128) == 0 )
 {
  // 获得主机ip地址
  struct hostent * pHost;
  pHost = gethostbyname(HostName);
  
  int j;
  int h_length=4;
  for( j = 0; j<h_length; j++ )
  {
   CString addr;   
   if( j > 0 )
    StrIP += ".";   
   addr.Format("%u", (unsigned int)((unsigned char*)pHost->h_addr_list[0])[j]);
   StrIP += addr;
  }  
 } 
 sprintf(svrIp,"%s",StrIP);
}

CString CUtilFunc::GetSysTimeStr()
{
 CTime tt = CTime::GetCurrentTime();
 CString str;
 str.Format("%d-%d-%d %d:%d:%d",tt.GetYear(),tt.GetMonth(),tt.GetDay(),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
 return str;
}
int CUtilFunc::SetShareMem(char *param,int value)
{
 char sValue[512] = "\0";
 sprintf(sValue,"%d",value);
 int ret = SetShareMem(param,sValue);
 return ret;
}
int CUtilFunc::SetShareMem(char *param,char *value)
{
 HANDLE hMapping;  
 LPSTR StrData;  
 hMapping=CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,0x100,param);  
 if(hMapping==NULL)  
 {  
  //MessageBox("创建文件映像对象","信息提示",MB_OK);
  LogFile("创建文件映像对象 失败");
  return 0;
 }
 //将文件映射到一个进程的地址空间上
 StrData=(LPSTR)MapViewOfFile(hMapping,FILE_MAP_ALL_ACCESS,0,0,0);  
 if(StrData==NULL)  
 {   
  //MessageBox("文件映射失败","信息提示",MB_OK);
  LogFile("文件映射 失败");
  return 0;
 }
 //向映射内存写数据
 sprintf(StrData,value);    
 //释放映像内存
 UnmapViewOfFile(StrData);  

 return 1;
}
int CUtilFunc::GetShareMem(char *param,char *value)
{

 //创建文件映像对象
 HANDLE hMapping;  
 LPSTR StrData;  
 hMapping=CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,0x100,param);  
 if(hMapping==NULL)  
 {   
  LogFile("创建文件映像对象 失败");
  return 0;
 }
 //将文件映射到一个进程的地址空间上
 StrData=(LPSTR)MapViewOfFile(hMapping,FILE_MAP_ALL_ACCESS,0,0,0);  
 if(StrData==NULL)  
 {    
  LogFile("文件映射 失败");
  return 0;
 }
 //获取映像内存的数据量
 sprintf(value,"%s",StrData);

 //释放映像内存
 UnmapViewOfFile(StrData); 

 return 1;
}
CString CUtilFunc::GetFormatTimeStr(CTime &tt,int format)
{
 char year[10];
 char month[10];
 char day[10];
 char hour[10];
 char minutes[10];
 char second[10];

 int iyear = tt.GetYear();
 int imonth = tt.GetMonth();
 int iday = tt.GetDay();
 int ihour = tt.GetHour();
 int iminutes = tt.GetMinute();
 int isecond = tt.GetSecond();
 
 //year
 sprintf(year,"%d",iyear);
 //month
 if (imonth<10)
 {
  sprintf(month,"0%d",imonth);
 }
 else
 {
  sprintf(month,"%d",imonth);
 }
 //day
 if (iday<10)
 {
  sprintf(day,"0%d",iday);
 }
 else
 {
  sprintf(day,"%d",iday);
 }
 //hour
 if (ihour<10)
 {
  sprintf(hour,"0%d",ihour);
 }
 else
 {
  sprintf(hour,"%d",ihour);
 }
 //minutes
 if (iminutes < 10)
 {
  sprintf(minutes,"0%d",iminutes);
 }
 else
 {
  sprintf(minutes,"%d",iminutes);
 }
 //second
 if (isecond<10)
 {
  sprintf(second,"0%d",isecond);
 }
 else
 {
  sprintf(second,"%d",isecond);
 }

 CString str;
 if(format == 0)
 {
  str.Format(_T("%s-%s-%s %s:%s:%s"),year,month,day,hour,minutes,second);
 }
 else
 {
  str.Format(_T("%s%s%s%s%s%s"),year,month,day,hour,minutes,second);
 }
 return str;
}
//idx = 0: 当前天
//idx = -1:前一天
//idx = 1: 后一天
CString CUtilFunc::GetFormatDateStr(int idx,int format)
{
 //CTime   tt  = CTime::GetCurrentTime();

 COleDateTime tt;
 tt = COleDateTime::GetCurrentTime();
 if(idx > 0)
 {
  tt = tt + COleDateTimeSpan(1,0,0,0);//
 }
 if(idx < 0)
 {
  tt = tt - COleDateTimeSpan(abs(idx),0,0,0);//
 } 

 char year[10];
 char month[10];
 char day[10];
 

 int iyear  = tt.GetYear();
 int imonth = tt.GetMonth();
 int iday   = tt.GetDay();
 
 
 //year
 sprintf(year,"%d",iyear);
 //month
 if (imonth<10)
 {
  sprintf(month,"0%d",imonth);
 }
 else
 {
  sprintf(month,"%d",imonth);
 }
 //day
 if (iday<10)
 {
  sprintf(day,"0%d",iday);
 }
 else
 {
  sprintf(day,"%d",iday);
 }
 

 CString str;
 if(format == 0)
 {
  str.Format(_T("%s-%s-%s"),year,month,day);
 }
 else
 {
  str.Format(_T("%s 年 %s 月 %s 日"),year,month,day);
 }
 return str;
}
CString CUtilFunc::GetFormatTimeStr(int y,int m,int d,int h,int mi,int s)
{
 char year[10];
 char month[10];
 char day[10];
 char hour[10];
 char minutes[10];
 char second[10];

 int iyear = y;
 int imonth = m;
 int iday = d;
 int ihour = h;
 int iminutes = mi;
 int isecond = s;
 
 //year
 sprintf(year,"%d",iyear);
 //month
 if (imonth<10)
 {
  sprintf(month,"0%d",imonth);
 }
 else
 {
  sprintf(month,"%d",imonth);
 }
 //day
 if (iday<10)
 {
  sprintf(day,"0%d",iday);
 }
 else
 {
  sprintf(day,"%d",iday);
 }
 //hour
 if (ihour<10)
 {
  sprintf(hour,"0%d",ihour);
 }
 else
 {
  sprintf(hour,"%d",ihour);
 }
 //minutes
 if (iminutes < 10)
 {
  sprintf(minutes,"0%d",iminutes);
 }
 else
 {
  sprintf(minutes,"%d",iminutes);
 }
 //second
 if (isecond<10)
 {
  sprintf(second,"0%d",isecond);
 }
 else
 {
  sprintf(second,"%d",isecond);
 }

 CString str;
 str.Format(_T("%s-%s-%s %s:%s:%s"),year,month,day,hour,minutes,second);
 
 return str;
}
CString CUtilFunc::GetFormatTimeStrBeg(CTime &tt )
{
char year[10];
 char month[10];
 char day[10];
 char hour[10];
 char minutes[10];
 char second[10];

 int iyear = tt.GetYear();
 int imonth = tt.GetMonth();
 int iday = tt.GetDay();
 int ihour = tt.GetHour();
 int iminutes = tt.GetMinute();
 int isecond = tt.GetSecond();
 
 //year
 sprintf(year,"%d",iyear);
 //month
 if (imonth<10)
 {
  sprintf(month,"0%d",imonth);
 }
 else
 {
  sprintf(month,"%d",imonth);
 }
 //day
 if (iday<10)
 {
  sprintf(day,"0%d",iday);
 }
 else
 {
  sprintf(day,"%d",iday);
 }
 
 
 CString str;
 str.Format(_T("%s-%s-%s 00:00:00"),year,month,day);
 
 return str;

}
CString CUtilFunc::GetFormatTimeStrEnd(CTime &tt)
{
 char year[10];
 char month[10];
 char day[10];
 char hour[10];
 char minutes[10];
 char second[10];

 int iyear = tt.GetYear();
 int imonth = tt.GetMonth();
 int iday = tt.GetDay();
 int ihour = tt.GetHour();
 int iminutes = tt.GetMinute();
 int isecond = tt.GetSecond();
 
 //year
 sprintf(year,"%d",iyear);
 //month
 if (imonth<10)
 {
  sprintf(month,"0%d",imonth);
 }
 else
 {
  sprintf(month,"%d",imonth);
 }
 //day
 if (iday<10)
 {
  sprintf(day,"0%d",iday);
 }
 else
 {
  sprintf(day,"%d",iday);
 }
 

 CString str;
 str.Format(_T("%s-%s-%s 23:59:59"),year,month,day);
 
 return str;
}
string CUtilFunc::GetSysTimeFormatStr(int format)
{
 CTime   tt  = CTime::GetCurrentTime();
 CString str = GetFormatTimeStr(tt,format);
 return str.GetBuffer(0);
}

DWORD CUtilFunc::GetNowTimeStamp()
{
 CTime tt = CTime::GetCurrentTime();
 DWORD lt = (tt.GetHour()*60 + tt.GetMinute()) * 60 +tt.GetSecond();
 return lt;
}
 
void CUtilFunc::ClearList(list<string> &list_char)
{
 list_char.clear();
}
void CUtilFunc::LoadBuf2List(list<string> &list_char,char *inBuf,char ch) //ch 为分割标志
{
 /*
 char *sBuf = inBuf;
 char *buf = NULL;
// //DebugInfo("CUtilFunc::LoadBuf2List:inbuf = %s",inBuf);
 list_char.clear();
 
 char *pn = strchr(sBuf,ch);
 while (pn)
 {
  char szBuf[RULE_LEN];
  memset(szBuf,'\0',RULE_LEN);
  strncpy(szBuf,sBuf,pn-sBuf);
 // //DebugInfo("szBuf = %s",szBuf);
  string buf = string(szBuf);
  list_char.push_back(buf);
 // //DebugInfo("list_char.size = %d",list_char.size());
  sBuf = pn+1;
  pn = strchr(sBuf,'*');
 }
 */
}
DWORD CUtilFunc::EraseString(vector<string> &vec_str,string str)
{
 vector<string>::iterator iter = vec_str.begin();
 for(;iter != vec_str.end(); iter++)
 {
  if(iter->compare(str) == 0) //表示此地址已经存在
  {
   vec_str.erase(iter);
   break;
  }
 }
  
 return vec_str.size();
}
DWORD CUtilFunc::UniqueCopyString(vector<string> &vecFrom,vector<string> &vecTo)
{
 DWORD num   = vecFrom.size();
 vecTo.resize(num);
 
 std::sort(vecFrom.begin(),vecFrom.end());
 vector<string>::iterator iter_del = std::unique_copy(vecFrom.begin(),vecFrom.end(),vecTo.begin());
  
 //全部变成小写
 num = vecTo.size(); 
 for(DWORD i = 0;i<num;i++)
 {
  std::transform(vecTo[i].begin(),vecTo[i].end(),vecTo[i].begin(),tolower);
 }
 return num;
}
BOOL CUtilFunc::CheckExistBuf(char *str, char *subStr)
{
 //检测str中是否含有subStr
 //1.将其load 进入一个list
 //2.在这个list中查找是否有这个subStr
 BOOL bFlag = FALSE;
 list<string> list_1;
 char *p = NULL;
 LoadBuf2List(list_1,str);

 list<string>::iterator iter = list_1.begin();
 for (;iter != list_1.end();iter ++)
 {
  if(strcmp((*iter).c_str() ,subStr) == 0)
  {
   bFlag = TRUE;  
  }
 }
 
 return bFlag;
}
//精确判断
BOOL CUtilFunc::CheckExitList(list<string> &list_char,string buf)
{
 if (list_char.empty())
 {
  return FALSE;
 }
 list<string>::iterator iter = list_char.begin();
 for (;iter != list_char.end();iter++)
 {
  string &str = *iter;
  const char *p = str.c_str();
  const char *q = buf.c_str();
  if(stricmp(p,q)== 0)  
  {
   //TRACE("p = %s,q= %s\n",p,q);
   return TRUE;
  }
 } 
 
 return FALSE;
}
//模糊判断
BOOL CUtilFunc::CheckExitList2(list<string> &list_char,string buf)
{
 if (list_char.empty())
 {
  return FALSE;
 }
 list<string>::iterator iter = list_char.begin();
 for (;iter != list_char.end();iter ++)
 {
  char *p = const_cast<char*>((*iter).c_str());
  char *q = const_cast<char*>(buf.c_str());
  if (strstr(p,q) != NULL || strstr(q,p) != NULL)
  {
   return TRUE;
  }  
 }
 return FALSE;
}
BOOL CUtilFunc::CheckUrl(const char *url)
{
 char *va = "://0123456789abcdefghijklmnopqrstuvwxyz+-*/[]{}\|?/><,.()*&^%$#@!~`;',./=-";
 char *vb = "abcdefghijklmnopqrstuvwxyz";
 int len  = strlen(url);
 int len2 = strlen(va);
 int len3 = strlen(vb);
 for(int i = 0;i<len;i++)
 {
  char c = url[i];
  bool find = false;
  for(int j = 0;j<len2;j++)
  {
   if(c == va[j])
   {
    find = true;
    break;
   }
  }
  if(!find)
   return 0;
 }

 //判断网址中是否没有字母存在
 bool find = false;
 for(int i = 0;i<len;i++)
 {  
  char c = url[i];  
  for(int j = 0;j<len3;j++)
  {
   if(c == va[j])
   {
    find = true;
    break;
   }
  }  
 }
 if(!find)
  return 0;

 if(strstr(url,".") == NULL) return 0;
 return 1;
}
void CUtilFunc::GetMainPath(char *sFolderName,int from )
{
 char szFullPath[MAX_PATH] = "\0";
 char szName[MAX_PATH] = "\0";
 if(from == 1)
 {
  ::GetModuleFileName(NULL,szFullPath,MAX_PATH); 
  strcpy(szName,strrchr(szFullPath,'\\')+1);

  strncpy(sFolderName,szFullPath,strlen(szFullPath) - strlen(szName));
 }
 else
 {
  //从注册表获取
 
  HKEY hKey;
  DWORD dwRet = ::RegCreateKey(HKEY_CURRENT_USER,"Software\\EHome",&hKey);
  if(dwRet == ERROR_SUCCESS && hKey != NULL)
  {
    char  szData[MAX_PATH] = "\0";
   DWORD type = REG_SZ;  
   DWORD size = MAX_PATH; 
   DWORD dwErr = 0;
   dwRet = ::RegQueryValueExA(hKey,"Path",0,&type,(LPBYTE)szData,&size);
   
   if(dwRet == ERROR_SUCCESS)
   {  
    char *pr = strrchr(szData,'\\');
    int pos = strlen(szData) - strlen(pr);
    szData[pos] = '\0';
    strcpy(sFolderName,szData);
   }
   else
   {
    CUtilFunc::GetMainPath(sFolderName,1);

   // dwErr = ::GetLastError();
   // LogFile("从注册表获取主目录失败:err = %d",dwErr);    
   }
   ::RegCloseKey(hKey);
  }
 }
}
void CUtilFunc::GetMainAppName(char *sMainAppName)
{
 char sIniFile[MAX_PATH] = "\0";
 char sMainFolder[MAX_PATH] = "\0";
 GetMainPath(sMainFolder,2);
 sprintf(sIniFile,"%s\\EHomeWin.dll",sMainFolder);
 ::GetPrivateProfileString("EHome","name","EHomeDemo.exe",sMainAppName,MAX_PATH,sIniFile);
}
HWND CUtilFunc::GetWindowHWND(char *sCaption)
{
 //Server Socket    //ServerSocket
 return NULL;
}
CString CUtilFunc::GetFileNameFromPID(DWORD dwPid)
{
 CString sPath = GetFullPathFromPID(dwPid);
 int pos = sPath.ReverseFind('\\');
 CString sName = sPath.Mid(pos+1);
 return sName;
}
CString CUtilFunc::GetFullPathFromPID(DWORD dwPid)
{
 CString sFullPath = "";

 BOOL bFindD3D = FALSE;
 //就查询一下这个进程所调用的模块列表,如果发现有d3d9.dll,则说明使用了d3d
 HANDLE hSnapshotInner = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,dwPid);
 if (hSnapshotInner != INVALID_HANDLE_VALUE)
 { 
  BOOL bRet = FALSE;
  MODULEENTRY32 mInfo;
  mInfo.dwSize = sizeof(MODULEENTRY32);
  for (bRet = Module32First(hSnapshotInner,&mInfo);bRet;bRet = Module32Next(hSnapshotInner,&mInfo))
  {
   sFullPath.Format("%s",mInfo.szExePath);
   break;
  }
  CloseHandle(hSnapshotInner);
 }
 return sFullPath;
}
BOOL CUtilFunc::CheckExistProc(DWORD dwPid)

 BOOL bFind = FALSE;
 //就查询一下这个进程所调用的模块列表,如果发现有d3d9.dll,则说明使用了d3d
 HANDLE hSnapshotInner = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,dwPid);
 if (hSnapshotInner != INVALID_HANDLE_VALUE)
 {
  bFind = 1;
  CloseHandle(hSnapshotInner);
 }
 return bFind;
}
BOOL CUtilFunc::CheckExistProc(const char *szName)
{
 DWORD dw = GetPIDFromName(szName);
 return dw != 0;
}
//获取进程列表
DWORD CUtilFunc::LoadProcList(vector<string> &vecProc)
{
 DWORD dwProcessID = 0;
 DWORD nProcess    = 0;
 HANDLE snapshot=CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0) ;
 if(snapshot == NULL)
  return FALSE ;
 SHFILEINFO shSmall;
 PROCESSENTRY32 processinfo ;
 processinfo.dwSize=sizeof(processinfo) ;
 BOOL status=Process32First(snapshot,&processinfo) ;
 while (status)
 {
  ZeroMemory(&shSmall, sizeof(shSmall));  
  SHGetFileInfo(processinfo.szExeFile,0,&shSmall,sizeof(shSmall),SHGFI_ICON|SHGFI_SMALLICON);
  ::DestroyIcon(shSmall.hIcon);
  
  vecProc.push_back(processinfo.szExeFile);
  
  status = Process32Next (snapshot, &processinfo) ;
  nProcess++;  
 }
 CloseHandle(snapshot);
 return nProcess;
}

DWORD CUtilFunc::LoadProcList(vector<DWORD> &vecPid,vector<string> &vecProc)
{
 DWORD dwProcessID = 0;
 DWORD nProcess    = 0;
 HANDLE snapshot=CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0) ;
 if(snapshot == NULL)
  return FALSE ;
 SHFILEINFO shSmall;
 PROCESSENTRY32 processinfo ;
 processinfo.dwSize=sizeof(processinfo) ;
 BOOL status=Process32First(snapshot,&processinfo) ;
 while (status)
 {
  ZeroMemory(&shSmall, sizeof(shSmall));  
  SHGetFileInfo(processinfo.szExeFile,0,&shSmall,sizeof(shSmall),SHGFI_ICON|SHGFI_SMALLICON);
  ::DestroyIcon(shSmall.hIcon);
  
  vecPid.push_back(processinfo.th32ProcessID);
  vecProc.push_back(processinfo.szExeFile);
  
  status = Process32Next (snapshot, &processinfo) ;
  nProcess++;  
 }
 CloseHandle(snapshot);
 int size = vecPid.size();
 return size;
}
DWORD CUtilFunc::GetPIDFromName(const char *szName)
{
 DWORD dwProcessID = 0;
 int   nProcess    = 0;
 HANDLE snapshot=CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0) ;
 if(snapshot == NULL)
  return FALSE ;
 
 SHFILEINFO shSmall;
 PROCESSENTRY32 processinfo ;
 processinfo.dwSize=sizeof(processinfo) ;
 BOOL status=Process32First(snapshot,&processinfo) ;
 
 while (status)
 {
  ZeroMemory(&shSmall, sizeof(shSmall));  
  SHGetFileInfo(processinfo.szExeFile,0,&shSmall,sizeof(shSmall),SHGFI_ICON|SHGFI_SMALLICON);
  //下面的释放非常重要
  ::DestroyIcon(shSmall.hIcon);
  if (stricmp(processinfo.szExeFile,szName) == 0)   
  {
   dwProcessID=processinfo.th32ProcessID;
   break;
  }
  status = Process32Next (snapshot, &processinfo) ;
  nProcess++;  
 }
 
 CloseHandle(snapshot);
 return dwProcessID;
}
DWORD CUtilFunc::GetPIDFromName2(const char *szName,DWORD notID)
{
 DWORD dwProcessID = 0;
 int   nProcess    = 0;
 HANDLE snapshot=CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0) ;
 if(snapshot == NULL)
  return FALSE ;
 SHFILEINFO shSmall;
 PROCESSENTRY32 processinfo ;
 processinfo.dwSize=sizeof(processinfo) ;
 BOOL status=Process32First(snapshot,&processinfo) ;
 while (status)
 {
  ZeroMemory(&shSmall, sizeof(shSmall));  
  SHGetFileInfo(processinfo.szExeFile,0,&shSmall,sizeof(shSmall),SHGFI_ICON|SHGFI_SMALLICON);
  ::DestroyIcon(shSmall.hIcon);
  if (stricmp(processinfo.szExeFile,szName) == 0)   
  {
   dwProcessID=processinfo.th32ProcessID;
   if(dwProcessID != notID)
   {
    break;
   }
  }
  status = Process32Next (snapshot, &processinfo) ;
  nProcess++;  
 }
 CloseHandle(snapshot);
 return dwProcessID;
}
string CUtilFunc::GetProcessAccount(DWORD dwPid)
{
 string sRet = "";
 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwPid);
 HANDLE hToken;
 DWORD  dwSize = 0;
 char   lpName[MAX_PATH] = "";
 char   lpDomain[MAX_PATH] = "";
 PTOKEN_USER pUserInfo = NULL;
 SID_NAME_USE SidType;
 string sUserName = "";
 TOKEN_PRIVILEGES Tkp;
 LUID    luid;
 BOOL pass = FALSE;

 if (hProcess > 0)
 {
  //先要提升权限
  
  pass = LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid);
  if (!pass) return "";

  pass = OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);
  if (pass)
  {
   Tkp.PrivilegeCount = 1;
   Tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
   Tkp.Privileges[0].Luid   = luid;
   pass = AdjustTokenPrivileges(hToken,FALSE,&Tkp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,0);
   CloseHandle(hToken);
   if (!pass)
   {
    //TRACE("AdjustTokenPrivileges Err = %x\n",GetLastError());
   }
  }
  else
  {
   //TRACE("OpenProcessToken Err = %x\n",GetLastError());
  }
  if(pass) 
  {
   pass = OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY|TOKEN_READ,&hToken);
   if (pass)
   {
    pass = GetTokenInformation(hToken,TokenUser,(LPVOID)pUserInfo,0,&dwSize);
    if (!pass)
    {
     if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
      pass = TRUE;
    }
    if (pass)
    {
     pUserInfo = (PTOKEN_USER)GlobalAlloc(GPTR,dwSize);
     pass = GetTokenInformation(hToken,TokenUser,pUserInfo,dwSize,&dwSize);
     if (pass)
     {
      pass = LookupAccountSid(NULL,pUserInfo->User.Sid,lpName,&dwSize,lpDomain,&dwSize,&SidType);
      if (pass)
      {
       //TRACE("UserName = %s\n",lpName);
       //TRACE("DomainName = %s\n",lpDomain);
       sUserName = lpName;
      }
     }
     CloseHandle(hToken);
    }
   }
  }
 } 
 CloseHandle(hProcess);
 return sUserName;
}
BOOL CUtilFunc::KillProcess(const char *szName,DWORD dwProcessID)

 CUtilFunc::LogFile("强行关闭进程:[%d][%s]",dwProcessID,szName);

 BOOL suc = FALSE;
 if(dwProcessID <= 0)
 {
  dwProcessID = GetPIDFromName(szName);
  if(dwProcessID == 0) return 1;

  HANDLE hProcess=::OpenProcess(PROCESS_TERMINATE,FALSE,dwProcessID);
  if (hProcess > 0)
  {
   suc = ::TerminateProcess(hProcess,0);
   CloseHandle(hProcess);
  } 
  else
  {
   suc = 1;
  }
 }
 else
 {
  HANDLE hProcess=::OpenProcess(PROCESS_TERMINATE,FALSE,dwProcessID);
  if (hProcess)
  {
   suc = ::TerminateProcess(hProcess,0);
   CloseHandle(hProcess);
  }  
  else
  {
   suc = 1;
  }
 } 
 return suc;

}
DWORD CUtilFunc::GetFileCheckSum(string sPath)
{
 DWORD dwHeadSum  = 0;
 DWORD dwCheckSum = 0;
 CString sRet;
 DWORD dwRet = MapFileAndCheckSum((PSTR)sPath.c_str(),&dwHeadSum,&dwCheckSum);
 if (dwRet == CHECKSUM_SUCCESS)
 {
  return dwCheckSum;
 }

 return 0;
}
BOOL CUtilFunc::StartProcess(char *szPath,int mode)
{
 ShellExecute(NULL,"Open",szPath,"","",mode) ;
 return TRUE;
 /*
 SHELLEXECUTEINFO Info;    
 memset (&Info, 0, sizeof(Info)) ;
 Info.cbSize=sizeof (Info) ;
 Info.lpVerb="open" ;
 Info.lpFile=szPath;
 Info.lpParameters=NULL;
 Info.fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSEPROCESS ;
 Info.nShow=mode;
 return ShellExecuteEx (&Info);
 */
}
BOOL CUtilFunc::CheckExistFile(const char *sFile)
{
 CFileFind finder;
 BOOL b = finder.FindFile(sFile);
 finder.Close();
 return b;
}
int CUtilFunc::ExecuteExe(char *sCmdline)
{
 PROCESS_INFORMATION proc; 
 STARTUPINFO start;
 SECURITY_ATTRIBUTES sa;

 ZeroMemory(&start,sizeof(STARTUPINFO));
 ZeroMemory(&proc, sizeof(PROCESS_INFORMATION));

 HANDLE ret;
 DWORD lngBytesRead;

 string sOutput = ""; 
 char sBuffer[4096];
 ZeroMemory(sBuffer,4096);

 sa.nLength    = sizeof(sa);
 sa.bInheritHandle  = TRUE;
 sa.lpSecurityDescriptor = NULL;
 

 start.cb    = sizeof(start);
 start.dwFlags   = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
// start.hStdOutput  = hWritePipe;
// start.hStdError   = hWritePipe;
 start.wShowWindow = SW_HIDE;

 int pass = CreateProcess(NULL,sCmdline,NULL,NULL,TRUE,0,NULL,NULL,&start,&proc);
 if(pass == 0)
 {
  //printf("Can not Create proc ,err = %x\n",GetLastError());
  return 0;
 }
// CloseHandle(hWritePipe);

 CloseHandle(proc.hProcess);
 CloseHandle(proc.hThread);
// CloseHandle(hReadPipe);

 return 1;
}

BOOL CUtilFunc::ExecuteAsAdmin(CHAR * pFile, CHAR *pParameters, int nShow,int bParam)
{
 OSVERSIONINFO  osvi;

 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
 GetVersionEx ( &osvi);
 DWORD dwMajor = osvi.dwMajorVersion;
 DWORD dwMior  = osvi.dwMinorVersion;

 BOOL    bRetVal;

 CString sParam;
 if(bParam== 0)
 {
  sParam.Format("\"%s\"", pParameters); 
 }
 else
 {
  sParam.Format("%s", pParameters); 
 }

 SHELLEXECUTEINFOA   ExInfo;  

 ZeroMemory(&ExInfo, sizeof(ExInfo));

 if(dwMajor >= 6 && dwMior >= 0) 
 { 
  ExInfo.cbSize          = sizeof(SHELLEXECUTEINFOW);
  ExInfo.hwnd            = NULL;
  ExInfo.fMask           = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
  ExInfo.lpVerb          = "runas";//_TEXT("runas");
  ExInfo.lpFile          = pFile;
  ExInfo.lpParameters    = sParam.GetBuffer();
  ExInfo.nShow           = nShow;
  
 }
 else
 {
   ExInfo.cbSize          = sizeof(SHELLEXECUTEINFOW);
  ExInfo.hwnd            = NULL;
  ExInfo.fMask           = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;  
  ExInfo.lpFile          = pFile;
  ExInfo.lpParameters    = sParam.GetBuffer();
  ExInfo.nShow           = nShow;
 }

 bRetVal = ShellExecuteExA(&ExInfo);
 if(!bRetVal)
 {
  LogFile("pFile = %s,sParam = %s ,执行失败!",pFile,sParam);
 }
 return bRetVal;
}

int  CUtilFunc::ExecuteIEWin7(char *sCmdline)
{

 PROCESS_INFORMATION proc; 
 STARTUPINFO start;
 SECURITY_ATTRIBUTES sa;

 ZeroMemory(&start,sizeof(STARTUPINFO));
 ZeroMemory(&proc, sizeof(PROCESS_INFORMATION));

 HANDLE ret;
 DWORD lngBytesRead;

 string sOutput = ""; 
 char sBuffer[4096];
 ZeroMemory(sBuffer,4096);
 
 sa.nLength    = sizeof(sa);
 sa.bInheritHandle  = TRUE;
 sa.lpSecurityDescriptor = NULL; 

 start.cb    = sizeof(start);
 start.dwFlags   = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
 start.wShowWindow = SW_HIDE;
 
 HANDLE hToken;
 TOKEN_PRIVILEGES tkp;
 OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
 LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid);
 tkp.PrivilegeCount = 1;  
 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 //取得进程关机特权
 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,  (PTOKEN_PRIVILEGES)NULL, 0);
 //int pass = CreateProcessAsUserA(hToken,"",sCmdline,NULL,NULL,TRUE,0,NULL,NULL,&start,&proc);
 int pass =CreateProcessAsUserA(hToken,"iexplore.exe",sCmdline,NULL,NULL,0,NULL,NULL,NULL,&start,&proc);
 //int pass = CreateProcess(NULL,sCmdline,NULL,NULL,TRUE,0,NULL,NULL,&start,&proc);
 if(pass == 0)
 {  
  return 0;
 }

 CloseHandle(proc.hProcess);
 CloseHandle(proc.hThread);
 return 1;
}
string CUtilFunc::ExecuteApp(char *sCmdline)
{
 PROCESS_INFORMATION proc; 
 STARTUPINFO start;
 SECURITY_ATTRIBUTES sa;

 ZeroMemory(&start,sizeof(STARTUPINFO));
 ZeroMemory(&proc, sizeof(PROCESS_INFORMATION));

 HANDLE ret;
 HANDLE hReadPipe;
 HANDLE hWritePipe;
 DWORD lngBytesRead;

 string sOutput = ""; 
 char sBuffer[4096];
 ZeroMemory(sBuffer,4096);

 sa.nLength    = sizeof(sa);
 sa.bInheritHandle  = TRUE;
 sa.lpSecurityDescriptor = NULL;

 BOOL pass = CreatePipe(&hReadPipe,&hWritePipe,&sa,0);
 if(pass == 0)
 {
  //printf("Crate Pipe Failed,err = %x.\n",GetLastError());
  return "";
 }

 start.cb    = sizeof(start);
 start.dwFlags   = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
 start.hStdOutput  = hWritePipe;
 start.hStdError   = hWritePipe;
 start.wShowWindow = SW_HIDE;

 pass = CreateProcess(NULL,sCmdline,NULL,NULL,TRUE,0,NULL,NULL,&start,&proc);
 if(pass == 0)
 {
  //printf("Can not Create proc ,err = %x\n",GetLastError());
  return "";
 }
 CloseHandle(hWritePipe);

 do
 { 
  pass = ReadFile(hReadPipe,sBuffer,4095,&lngBytesRead,NULL);
  if (pass)
  {
   sOutput += sBuffer;
  }

 }while(pass != 0);

 CloseHandle(proc.hProcess);
 CloseHandle(proc.hThread);
 CloseHandle(hReadPipe);

 return sOutput;
}
void CUtilFunc::SetFileAttributes(char *sPath, DWORD dwAttrs)
{
 DWORD dwOldAttrs = GetFileAttributes(sPath);     
 if (!(dwAttrs & dwOldAttrs))
 {
  SetFileAttributes(sPath,dwOldAttrs|dwAttrs);   
 }
}
BOOL CUtilFunc::GetSelectedListItem(CListCtrl &lst,int iSubItem ,char *sItemText)
{
 BOOL flag = FALSE;
 for (int i = 0;i<lst.GetItemCount();i++)
 {
  if (lst.GetItemState(i,TVIS_SELECTED) == TVIS_SELECTED)
  {
   flag = TRUE;
   if (iSubItem >=0)
   {
    CString sText = lst.GetItemText(i,iSubItem);
    sprintf(sItemText,"%s",sText);
   }
  }
 }
 return flag;
}

int CUtilFunc::ExportDllSys(HMODULE hModule,UINT resID,LPCTSTR typeName,LPCTSTR dllName)
{
  //HRSRC hRsrc     = FindResource(NULL,"IDR_DLL_WINIO","SYS_DLL");
 HRSRC   hRsrc   =   FindResource(hModule, MAKEINTRESOURCE(resID),typeName);

 //HRSRC hRsrc     = FindResource(hModule,resName,typeName);
  if (hRsrc == NULL) return 0;

  HGLOBAL hGlobal = ::LoadResource(hModule,hRsrc);
  if (hGlobal == NULL) return -1;
 
  LPVOID   pRes   =   LockResource(hGlobal); 
  DWORD   dwSize  =   SizeofResource(hModule,   hRsrc);   
 
  char sMainFolder[MAX_PATH];
  char sDllName[MAX_PATH];
  GetMainPath(sMainFolder); 
  sprintf(sDllName,"%s\\%s",sMainFolder,dllName);

  BOOL bDel = DeleteFile(sDllName);
 
  FILE *fp = fopen(sDllName,"a+b");
  if (fp)
  {
   fwrite(pRes,dwSize,1,fp);
   fclose(fp);
  } 
 
 SetFileHidden(sDllName);
  return 1;
}

BOOL CUtilFunc::SetFileHidden(CString sFilePath)
{
 SetFileAttributes(sFilePath.GetBuffer(0),FILE_ATTRIBUTE_HIDDEN);
 
 return 1;
}

void CUtilFunc::LogFile(const char *slog,...)
{
 char sLog[1024*2] = "\0";

 va_list args; 
 va_start(args,slog); 
 vsprintf(sLog,slog,args);
 va_end(args);

 char szMainPath[MAX_PATH] = "\0"; 
 char szMainFolder[MAX_PATH] = "\0"; 
 char szMainName[MAX_PATH] = "\0"; 

 HMODULE hModule = NULL;
 ::GetModuleFileName(hModule,szMainPath,MAX_PATH);
 char *p = (char*)strrchr(szMainPath,'\\');
 if(p == NULL ) return ;
 char *q = (char*)strrchr(p,'.');
 if(q)
 {
  strncpy(szMainName,p+1,strlen(p+1) - strlen(q));
 }
 else
 {
  strcpy(szMainName,p);
 }
 
 CUtilFunc::GetMainPath(szMainFolder,2);
 sprintf(szMainPath,"%s\\%s.log",szMainFolder,szMainName);

 /*
 char *p = strrchr(szMainPath,'.');
 int len = strlen(szMainPath) - strlen(p);
 szMainPath[len] = '\0'; 
 strcat(szMainPath,".log");
 */

 
 CString sTime = GetSysTimeStr();

 FILE  *fp = fopen(szMainPath,"a+");
 if(fp != NULL)
 {
  fprintf(fp,"[%s] ",sTime);
  fprintf(fp,"%s\n",sLog);
  fclose(fp);
 } 
}

/******************************************************************************
*
* FUNCTION: Split
*
* PURPOSE: Split a delimited line into components
*
******************************************************************************/
int CUtilFunc::Split( char * line, char delimiter, char * items[] )
{
 int  cnt = 0;

 for (;;)  {
  // Add prefix to list of components  
  items[cnt++] = line;

  // Check for more components
  line = strchr( line, delimiter );
  if ( line == NULL )
   return cnt;

  // Terminate previous component and move to next
  *line++ = '\0';
 }  
 return 0;
}
int CUtilFunc::ConvertUtf8ToANSI(char *sReadData,char *outData)
{
 //UTF-8 --> UNICODE --> ANSI
  
 int nLen  = strlen(sReadData); 
 
 //UTF-8 --> UNICODE
 int nWLen = ::MultiByteToWideChar(CP_UTF8,NULL,sReadData,nLen,NULL,0);
 WCHAR *wsReadData = new WCHAR[nWLen +1];
 MultiByteToWideChar(CP_UTF8,0,sReadData,nLen,wsReadData,nWLen);
 wsReadData[nWLen] = '\0';
 //MessageBoxW(NULL,wsReadData,(const unsigned short*)("wsReadData"),MB_OK);

 
 //UNICODE --> ANSI
 int ansiLen = WideCharToMultiByte(CP_ACP,NULL,wsReadData,wcslen(wsReadData),NULL,0,NULL,NULL);
 char *sReadData2 = new char[ansiLen+1];
 WideCharToMultiByte(CP_ACP,NULL,wsReadData,wcslen(wsReadData),sReadData2,ansiLen,NULL,NULL);
 sReadData2[ansiLen] = '\0';
 //MessageBox(NULL,sReadData2,"ReadData2",MB_OK);

 strcpy(outData,sReadData2);

 delete []wsReadData;
 wsReadData = NULL;

 delete []sReadData2;
 sReadData2 = NULL;

 return nLen;
}
int CUtilFunc::SaveUtf8ToFile(char *sReadData,char *xmlFile)
{
 //UTF-8 --> UNICODE --> ANSI
  
 int nLen  = strlen(sReadData); 
 
 //UTF-8 --> UNICODE
 int nWLen = ::MultiByteToWideChar(CP_UTF8,NULL,sReadData,nLen,NULL,0);
 WCHAR *wsReadData = new WCHAR[nWLen +1];
 MultiByteToWideChar(CP_UTF8,0,sReadData,nLen,wsReadData,nWLen);
 wsReadData[nWLen] = '\0';
 //MessageBoxW(NULL,wsReadData,(const unsigned short*)("wsReadData"),MB_OK);

 
 //UNICODE --> ANSI
 int ansiLen = WideCharToMultiByte(CP_ACP,NULL,wsReadData,wcslen(wsReadData),NULL,0,NULL,NULL);
 char *sReadData2 = new char[ansiLen+1];
 WideCharToMultiByte(CP_ACP,NULL,wsReadData,wcslen(wsReadData),sReadData2,ansiLen,NULL,NULL);
 sReadData2[ansiLen] = '\0';
 //MessageBox(NULL,sReadData2,"ReadData2",MB_OK);

 FILE *fp = fopen(xmlFile,"w");
 if (fp)
 {
  fwrite(sReadData2,1,strlen(sReadData2),fp);
  fclose(fp);
 }

 delete []wsReadData;
 wsReadData = NULL;

 delete []sReadData2;
 sReadData2 = NULL;

 return nLen;
}
int CUtilFunc::ParseVer(char* ver,int &major,int &minor,int &revi)
{
 char a[10] = "\0";
 char b[10] = "\0";
 
 char *p = strstr(ver,".");
 if(p == NULL) return 0;

 int len = strlen(ver) - strlen(p);
 if(len <= 0) return 0;
 strncpy(a,ver,len);

 char *q = strstr(p+1,".");
 if(q == NULL) return 0;
 len = strlen(p+1) - strlen(q);
 if(len <= 0) return 0;
 strncpy(b,p+1,len);

 char *c = q+1;
 if(c == NULL) return 0;

 major = atoi(a);
 minor = atoi(b);
 revi  = atoi(c);

 return 1;
}
int CUtilFunc::CompareVer(char *ver1,char *ver2)//比较版本
{
 int major1,minor1,revi1;
 int major2,minor2,revi2;
 ParseVer(ver1,major1,minor1,revi1);
 ParseVer(ver2,major2,minor2,revi2);
 if(major1 > major2) return 1;
 if(major1 < major2) return -1;
 if(major1 == major2)
 {
  if(minor1 > minor2) return 1;
  if(minor1 < minor2) return -1;
  if(minor1 == minor2)
  {
   if(revi1 > revi2) return 1;
   if(revi1 < revi2) return -1;
   if(revi1 == revi2) return 0;
  }
 }
 return 0;
}
string CUtilFunc::GetRuleText(UINT nID)
{
 string sText;
 /*
 int nSize = sizeof(nRuleID)/sizeof(SRule);
 for (int i = 0;i<nSize;i++)
 {
  if(nRuleID[i].nID == nID)
  {
   sText = nRuleID[i].sCmd;
  }
 }
 */
 return sText;
}
BOOL CUtilFunc::GetFileVersions(char * pFilePath, FILE_VERSION * pVerInfo)
{
 DWORD dwDummyHandle; // will always be set to zero
 DWORD dwLen;
 BYTE * pVersionInfo;
 BOOL bRetVal;
 
 VS_FIXEDFILEINFO FileVersion;

 memset(pVerInfo, 0, sizeof(FILE_VERSION));

 const char *name = strrchr(pFilePath,'\\');
 if(name != NULL)
 {
  strcpy(pVerInfo->szProcName,name + 1);
 }

 struct TRANSLATION {
  WORD langID;   // language ID
  WORD charset;   // character set (code page)
 } Translation;

 HMODULE  hVerDll;
 hVerDll = GetModuleHandleA("VERSION.dll");
 if(hVerDll == NULL)
        hVerDll = LoadLibraryA("VERSION.dll");
 if(hVerDll == NULL)
  return FALSE;

 typedef DWORD (WINAPI *Fun_GetFileVersionInfoSizeA)(CHAR *, DWORD *);
 typedef BOOL  (WINAPI *Fun_GetFileVersionInfoA)(CHAR *, DWORD, DWORD, LPVOID);
 typedef BOOL  (WINAPI *Fun_VerQueryValueA)(LPVOID, CHAR *, LPVOID, PUINT);


 Fun_GetFileVersionInfoSizeA  pGetFileVersionInfoSizeA;
 Fun_GetFileVersionInfoA   pGetFileVersionInfoA;
 Fun_VerQueryValueA    pVerQueryValueA;

 pGetFileVersionInfoSizeA = (Fun_GetFileVersionInfoSizeA)::GetProcAddress(hVerDll, "GetFileVersionInfoSizeA");
 pGetFileVersionInfoA  = (Fun_GetFileVersionInfoA)::GetProcAddress(hVerDll, "GetFileVersionInfoA");
 pVerQueryValueA    = (Fun_VerQueryValueA)::GetProcAddress(hVerDll, "VerQueryValueA");

 
 Translation.langID = 0x0409; //
 Translation.charset = 1252;  // default = ANSI code page

 dwLen = pGetFileVersionInfoSizeA(pFilePath, &dwDummyHandle);
 if (dwLen == 0)
  return FALSE;

 pVersionInfo = new BYTE[dwLen]; // allocate version info
 bRetVal = pGetFileVersionInfoA(pFilePath, 0, dwLen, pVersionInfo);
 if(bRetVal == FALSE)
 {
  delete [] pVersionInfo;
  return FALSE;
 }

 VOID * pVI;
 UINT uLen;

 bRetVal = pVerQueryValueA(pVersionInfo, "\\", &pVI, &uLen);
 if(bRetVal == FALSE)
 {
  delete [] pVersionInfo;
  return FALSE;
 }

 memcpy(&FileVersion, pVI, sizeof(VS_FIXEDFILEINFO));

 bRetVal = pVerQueryValueA(pVersionInfo, "\\VarFileInfo\\Translation",
  &pVI, &uLen);
 if(bRetVal && uLen >= 4)
 {
  memcpy(&Translation, pVI, sizeof(TRANSLATION));
 }

 //BREAKIF(FileVersion.dwSignature != VS_FFI_SIGNATURE);

 CHAR  szQuery[1024];
 CHAR  * pVal;
 UINT  iLenVal;

 {
  sprintf(szQuery, "%d.%d.%d.%d",
   HIWORD(FileVersion.dwFileVersionMS), LOWORD(FileVersion.dwFileVersionMS),
   HIWORD(FileVersion.dwFileVersionLS), LOWORD(FileVersion.dwFileVersionLS));
  strncpy(pVerInfo->szVersion, szQuery, MAX_PATH);
 }

 {
  sprintf(szQuery, "\\StringFileInfo\\%04X%04X\\CompanyName",
   Translation.langID, Translation.charset);

  bRetVal = pVerQueryValueA(pVersionInfo, szQuery, (LPVOID*)&pVal, &iLenVal);
  if(bRetVal)
   strncpy(pVerInfo->szCompany, pVal, MAX_PATH);
  else
   strncpy(pVerInfo->szCompany, "", MAX_PATH);
 }

 {
  sprintf(szQuery, "\\StringFileInfo\\%04X%04X\\FileDescription",
   Translation.langID, Translation.charset);

  bRetVal = pVerQueryValueA(pVersionInfo, szQuery, (LPVOID*)&pVal, &iLenVal);
  if(bRetVal)
   strncpy(pVerInfo->szDescription, pVal, MAX_PATH);
  else
   strncpy(pVerInfo->szDescription, "", MAX_PATH);
 }

 delete [] pVersionInfo;
 return TRUE;
}
//从进程名称获取所有软件信息
BOOL CUtilFunc::GetFileVersions2(char * pFileName, FILE_VERSION * pVerInfo)
{
 DWORD dwId = GetPIDFromName(pFileName);
 if(dwId == 0) return FALSE;

 CString sPath = GetFullPathFromPID(dwId);
 BOOL b = GetFileVersions(sPath.GetBuffer(),pVerInfo);
 return b;
}
//从进程号获取所有软件信息
BOOL CUtilFunc::GetFileVersions2(DWORD dwId, FILE_VERSION * pVerInfo)
{
 CString sPath = GetFullPathFromPID(dwId);
 BOOL b = GetFileVersions(sPath.GetBuffer(),pVerInfo);
 return b;
}
BOOL CUtilFunc::GetProcInfo(IN CString procPath,OUT CString &name,OUT CString &proc,OUT CString &author)
{
 name = "";
 proc = "";
 author = "";
 CString sModuleName = procPath;
 CVFXVersionRes VersionRes;
 CVFXVersionInfo VersionInfo;

 sModuleName.TrimLeft();
 sModuleName.TrimRight();

 proc   = procPath.Mid(procPath.ReverseFind('\\')+1);

 // Note: passing NULL as a module name here will return the
 // version information for the current module
 if(VersionInfo.GetVersionInfo(VersionRes,
  sModuleName.IsEmpty() ? (LPCTSTR)NULL : (LPCTSTR)sModuleName))
  {
   name   = VersionRes.m_sProductName;   
   author = VersionRes.m_sCompanyName;
        // Display the whole VS_VERSION_INFO block  
   /*
  m_listVsVersionInfo.AddString("*---------------------------------------------------------*");
  m_listVsVersionInfo.AddString("ModuleName: " + VersionRes.m_sModuleName);
  m_listVsVersionInfo.AddString("FileVersion: " + VersionRes.m_sFileVersion);
  m_listVsVersionInfo.AddString("ProdVersion: " + VersionRes.m_sProdVersion);
  m_listVsVersionInfo.AddString("CompanyName: " + VersionRes.m_sCompanyName);
  m_listVsVersionInfo.AddString("FileDescription: " + VersionRes.m_sFileDescription);
  m_listVsVersionInfo.AddString("InternalName: " + VersionRes.m_sInternalName);
  m_listVsVersionInfo.AddString("LegalCopyright: " + VersionRes.m_sLegalCopyright);
  m_listVsVersionInfo.AddString("OriginalFileName: " + VersionRes.m_sOriginalFileName);
  m_listVsVersionInfo.AddString("ProductName: " + VersionRes.m_sProductName);
  m_listVsVersionInfo.AddString("Comments: " + VersionRes.m_sComments);
  m_listVsVersionInfo.AddString("PrivateBuild: " + VersionRes.m_sPrivateBuild);
  m_listVsVersionInfo.AddString("PrivateBuild: " + VersionRes.m_sPrivateBuild);
  m_listVsVersionInfo.AddString("SpecialBuild: " + VersionRes.m_sSpecialBuild);
  */
   return 1;
 }
 return 0;
}
BOOL CUtilFunc::GetProcInfo(IN CString proc,OUT CString &name,OUT CString &author)
{
 DWORD   dwPid = CUtilFunc::GetPIDFromName(proc);
 CString sPath = CUtilFunc::GetFullPathFromPID(dwPid);
 BOOL b = GetProcInfo(sPath,name,proc,author);
 return b;
}
void CUtilFunc::SetTransparent(CWnd *pWnd)
{
 HINSTANCE hInst = LoadLibrary("User32.DLL");
 if(hInst)
 {
  typedef BOOL (WINAPI *MYFUNC)(HWND,COLORREF,BYTE,DWORD);
  MYFUNC fun = NULL;
  //取得SetLayeredWindowAttributes()函数指针
  fun=(MYFUNC)GetProcAddress(hInst, "SetLayeredWindowAttributes");
  if(fun)fun(pWnd->GetSafeHwnd(),0,128,2);
  FreeLibrary(hInst);
 } 
}

void CUtilFunc::SetCaptionBK(CWnd *pWndParent,UINT uID,CString sCaption)

 CWnd *pWnd=pWndParent->GetDlgItem(uID);
 if(!pWnd) return;
 
 //CDC *dc2 = pWnd->GetDC();
 CDC *dc2 = pWndParent->GetDC();
 //CPaintDC dc2(pWnd);  

 CRect Rect;
 pWnd->GetClientRect(&Rect); 
 Rect.top +=5;
 
 CBrush MyBrush;
 
 COLORREF ref = RGB(210,220,249);
 MyBrush.CreateSolidBrush(ref);
 CBrush *pOldBrush=dc2->SelectObject(&MyBrush);
 CPen pen(PS_SOLID,1,ref);  
 CPen *pOldPens = dc2->SelectObject(&pen); 
 CFont myFont;
 CFont *pOldFont=NULL;
 
 myFont.CreateFont(14,7,0,0,FW_BOLD,FALSE,0,0,0,0,0,0,0,_T("Arial"));
 pOldFont=dc2->SelectObject(&myFont);
 dc2->Rectangle(0,0,Rect.Width(),18);

 dc2->MoveTo(Rect.left,Rect.top);
 dc2->LineTo(Rect.left,Rect.bottom);
 dc2->LineTo(Rect.right,Rect.bottom);
 dc2->LineTo(Rect.right,Rect.top);
 dc2->LineTo(Rect.left,Rect.top);

 dc2->SetBkMode(TRANSPARENT);
 dc2->TextOut(18,2,sCaption);  

 dc2->SelectObject(pOldBrush);
 dc2->SelectObject(pOldPens);
 dc2->SelectObject(pOldFont);
 
 /*CBitmap Bmp;
 Bmp.LoadBitmap(IDB_BMP_BOOK);
 CDC memDC;
 memDC.CreateCompatibleDC((CDC*)dc2);
 memDC.SelectObject(&Bmp);
 dc2->BitBlt(0,0,20,15,&memDC,0,0,SRCCOPY);*/

 
}
int CUtilFunc::CreateProcessEx(char *cmd)
{
 STARTUPINFO si;
 PROCESS_INFORMATION pi;

 ZeroMemory( &si, sizeof(si) );
 si.cb = sizeof(si);
 ZeroMemory( &pi, sizeof(pi) );

// Start the child process.
    if( !CreateProcess( NULL,   // No module name (use command line)
        cmd,             // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        CREATE_NO_WINDOW,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        //printf( "CreateProcess failed (%d).\n", GetLastError() );
        return 0;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

 return 1;
}
bool CUtilFunc::DeleteDirectory(char* sDirName)
{
    CFileFind tempFind;
    char sTempFileFind[200] ;
   
    sprintf(sTempFileFind,"%s*.*",sDirName);
    BOOL IsFinded = tempFind.FindFile(sTempFileFind);
    while (IsFinded)
    {
        IsFinded = tempFind.FindNextFile();
       
        if (!tempFind.IsDots())
        {
            char sFoundFileName[200];
            strcpy(sFoundFileName,tempFind.GetFileName().GetBuffer(200));
           
            if (tempFind.IsDirectory())
            {
                char sTempDir[200];
                sprintf(sTempDir,"%s\%s",sDirName,sFoundFileName);
                DeleteDirectory(sTempDir);
            }
            else
            {
                char sTempFileName[200];
                sprintf(sTempFileName,"%s\%s",sDirName,sFoundFileName);
                DeleteFile(sTempFileName);
            }
        }
    }
    tempFind.Close();
    if(!RemoveDirectory(sDirName))
    {
        return FALSE;
    }
    return TRUE;
}

int CUtilFunc::ListFileInDirectory(char *sDirName,vector<CString> &vecFile,int dep)
{
 if(dep <= 0) return 0;

 CFileFind tempFind;
    char sTempFileFind[200] ;
   
    sprintf(sTempFileFind,"%s\\*.*",sDirName);
    BOOL IsFinded = tempFind.FindFile(sTempFileFind);
    while (IsFinded)
    {
        IsFinded = tempFind.FindNextFile();
       
        if (!tempFind.IsDots())
        {
            char sFoundFileName[200];
            strcpy(sFoundFileName,tempFind.GetFileName().GetBuffer(200));
           
            if (tempFind.IsDirectory())
            {
                char sTempDir[200];
                sprintf(sTempDir,"%s\\%s",sDirName,sFoundFileName);
               
    ListFileInDirectory(sTempDir,vecFile,--dep);
            }
            else
            {
                char sTempFileName[200];
                sprintf(sTempFileName,"%s\\%s",sDirName,sFoundFileName);
               
    vecFile.push_back(sFoundFileName);
            }
        }
    }
    tempFind.Close();
  
    return TRUE;
}

void CUtilFunc::ShowTrayIcon(char szIcon[],BOOL hide)
{
    HWND hWnd,hWndPaper;
    unsigned long lngPID;
    long ret,lngButtons;
    HANDLE hProcess;
    LPVOID lngAddress;
    long lngTextAdr,lngHwndAdr,lngHwnd,lngButtonID;
    char strBuff[1024]={0};
    char* str = NULL;
    char *pp = NULL;
 
    hWnd = FindWindow("Shell_TrayWnd", NULL);
    hWnd = FindWindowEx(hWnd, 0, "TrayNotifyWnd", NULL);
    hWndPaper = FindWindowEx(hWnd, 0, "SysPager", NULL);
    if(!hWndPaper)
        hWnd = FindWindowEx(hWnd, 0, "ToolbarWindow32", NULL);
    else
        hWnd = FindWindowEx(hWndPaper, 0, "ToolbarWindow32", NULL);
    ret = GetWindowThreadProcessId(hWnd, &lngPID);
    hProcess = OpenProcess(PROCESS_ALL_ACCESS
                            |PROCESS_VM_OPERATION
                            |PROCESS_VM_READ
                            |PROCESS_VM_WRITE,
                            0,
                            lngPID);
    lngAddress = VirtualAllocEx(hProcess,0, 0x4096, MEM_COMMIT, PAGE_READWRITE);
    lngButtons = SendMessage(hWnd, TB_BUTTONCOUNT, 0, 0);

    for(int i=0 ;i< lngButtons - 1;i++)
    {
        ret = SendMessage(hWnd,TB_GETBUTTON,i,long(lngAddress));
        ret = ReadProcessMemory(hProcess, LPVOID(long(lngAddress) + 16),&lngTextAdr,4,0);
        if(lngTextAdr != -1)
        {
            ret = ReadProcessMemory(hProcess, LPVOID(lngTextAdr),strBuff,1024,0);
            ret = ReadProcessMemory(hProcess, LPVOID(long(lngAddress) + 12),&lngHwndAdr,4,0);
            ret = ReadProcessMemory(hProcess, LPVOID(lngHwndAdr),&lngHwnd, 4,0);
            ret = ReadProcessMemory(hProcess, LPVOID(long(lngAddress) + 4),&lngButtonID,4,0);

  // ret = ::ReadProcessMemory(hProcess, LPVOID(long(lngAddress)), &tb, sizeof(TBBUTTON), 0);
  // ret = ::ReadProcessMemory(hProcess, LPVOID(tb.dwData), &tray, sizeof(TRAYDATA), 0);

            USES_CONVERSION;
            str = OLE2T((LPOLESTR)(strBuff));
            pp=strstr(str,szIcon);
            if(pp != NULL)
            { 
    if (hide)
    {
     SendMessage(hWnd,TB_HIDEBUTTON,lngButtonID,1);
    }
    else
    {
     SendMessage(hWnd,TB_HIDEBUTTON,lngButtonID,0);
    } 
    break;
            }
        }
    }
    VirtualFreeEx( hProcess,  lngAddress, 0, MEM_RELEASE);
    CloseHandle(hProcess);
}
int  CUtilFunc::CheckHasChinese(const char *str)
{
 int len = strlen(str);
 for(int i = 0;i<len;i++)
 {
  if(str[i] > 255 || str[i] < 0) return 1;
 }
 return 0;
}
CString CUtilFunc::GetTmpFolder(void)
{
 char Path[MAX_PATH];
 CString StrPath = "C:\\Documents and Settings\\Administrator\\My Documents";
 LPITEMIDLIST pidl;
 LPMALLOC pShellMalloc;
 if(SUCCEEDED(SHGetMalloc(&pShellMalloc)))
 {
  if(SUCCEEDED(SHGetSpecialFolderLocation(NULL,CSIDL_TEMPLATES,&pidl)))
  {
   if(SHGetPathFromIDList(pidl,Path))
   {
    StrPath.Format("%s",Path);
    //MessageBox("临时文件夹位于:"+StrPath,"提示信息",MB_OK);
   }
  }
 }
 pShellMalloc->Free(pidl);
 pShellMalloc->Release();
 return StrPath;
}
CString CUtilFunc::GetAppDataFolder(void)
{
 char Path[MAX_PATH];
 CString StrPath = "C:\\Documents and Settings\\Administrator\\Application Data";
 LPITEMIDLIST pidl;
 LPMALLOC pShellMalloc;
 if(SUCCEEDED(SHGetMalloc(&pShellMalloc)))
 {
  if(SUCCEEDED(SHGetSpecialFolderLocation(NULL,CSIDL_TEMPLATES,&pidl)))
  {
   if(SHGetPathFromIDList(pidl,Path))
   {
    StrPath.Format("%s",Path);
    StrPath.Replace("Templates","Application Data");
    //MessageBox("临时文件夹位于:"+StrPath,"提示信息",MB_OK);
   }
  }
 }
 pShellMalloc->Free(pidl);
 pShellMalloc->Release();
 return StrPath;
}
//

原创粉丝点击