一些工具函数(Need MFC Support)

 #include "stdafx.h"
#include "NTHelper.h"
#include <tlhelp32.h>
#ifdef _UNICODE
#include "afxpriv.h"
#endif
#include "atlbase.h"

-系统信息

OSTYPE CNTHelper::GetOSType()
{
OSVERSIONINFO vinfo;

vinfo.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
::GetVersionEx( &vinfo );

if( vinfo.dwPlatformId != VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion == 4        &&
     vinfo.dwMinorVersion == 0 )
{
     return WIN_95;
}
if( vinfo.dwPlatformId != VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion >= 4        &&
     vinfo.dwMinorVersion > 0        &&
     !( vinfo.dwMajorVersion == 4 && vinfo.dwMinorVersion == 90 ) )
{
     return WIN_98;
}
if( vinfo.dwPlatformId != VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion == 4        &&
     vinfo.dwMinorVersion == 90 )
{
     return WIN_ME;
}
if( vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion == 4        &&
     vinfo.dwMinorVersion == 0 )
{
     return WIN_NT;
}
if( vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion == 5        &&
     vinfo.dwMinorVersion == 0 )
{
     return WIN_2000;
}
if( vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT &&
     vinfo.dwMajorVersion == 5        &&
     vinfo.dwMinorVersion == 1 )
{
     return WIN_XP;
}

// Default always return Windows NT
return WIN_NT;
}

 

-文件目录操作

/
// Return the directory of the current module file
//
// Suppose current module file is: E:/Products/DataAnalyst/bin/DataAnalyst.exe
// It will return E:/Products/DataAnalyst/bin
//
CString CNTHelper::GetModuleFileDir()
{
DWORD dwLength, dwSize;
TCHAR szFileName [MAX_PATH];
CString strFileName;
int     nPos;

dwSize = sizeof (szFileName) / sizeof (szFileName [0]);
dwLength = ::GetModuleFileName (AfxGetInstanceHandle(), szFileName, dwSize);
if (dwLength <= 0)
{
     return _T("");
}

strFileName = szFileName;
nPos = strFileName.ReverseFind( '//' );
return strFileName.Left( nPos );
}

// 判断某个路径是目录还是文件
// 返回true:是目录
// 返回false:是文件
BOOL CNTHelper::IsDictionary(CString szPath)
{
CFileFind find;
BOOL     bResult = false;
CString szFile = _T("");

if( szPath.GetAt(szPath.GetLength()-1) == _T('//') )
{
     szFile = szPath;
     szFile += ( _T("*.*"));
}
else  
{
     szFile = szPath;
     szFile +=     _T("//*.*");
}

bResult = find.FindFile( szFile );  
find.Close();

return bResult;
}

// // 删除指定的文件或文件夹,isFile标记是删除文件还是文件夹
BOOL CNTHelper::DelFile(CString szPath, BOOL isFile)
{
BOOL bResult = true;

if (szPath.Compare( _T("")) == 0)// 目标不为空
     return bResult;

if (isFile)
{
     bResult = DeleteFile(szPath);  
}
else
{
     bResult = DeleteTree(szPath);
}

return bResult;
}

// 删除指定的文件夹中所有文件成功:
// 返回TRUE;否则,返回FALSE
BOOL CNTHelper::DeleteTree(CString szDirName)
{
BOOL Result = false;

Result = PreRemoveDirectory(szDirName);
Result = Result && RemoveDirectory(szDirName);

return Result;
}

// // 被DeleteTree调用,递归删除文件和文件夹
// 返回TRUE;否则,返回FALSE
BOOL CNTHelper::PreRemoveDirectory(CString szDirName)
{
LPTSTR lpBuffer;

UINT uSize;

CString fileName;

HANDLE hHeap;

BOOL result = true;

HANDLE hFindFile;

WIN32_FIND_DATA FindFileData;

uSize=(GetCurrentDirectory(0,NULL)) * sizeof(TCHAR);

hHeap=GetProcessHeap();

lpBuffer=(LPTSTR)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,uSize);

GetCurrentDirectory(uSize,lpBuffer);

if(lpBuffer!=szDirName){//调整当前目录
     SetCurrentDirectory(szDirName);
}

hFindFile=FindFirstFile(_T("*.*"),&FindFileData);

CString tFile;

if(hFindFile!=INVALID_HANDLE_VALUE)
{
     do{
      tFile=FindFileData.cFileName;

      if((tFile.Compare(_T("."))==0)||(tFile.Compare(_T(".."))==0)) continue;

      if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) // 目录
      {
       if(szDirName.GetAt(szDirName.GetLength() - 1) != _T('//'))
       {
        CString tmp = szDirName;
        tmp += _T("//");
        tmp += tFile;
        PreRemoveDirectory(tmp);
       }
       else
       {
        CString tmp = szDirName;
        tmp += tFile;
        PreRemoveDirectory(tmp);
       }

       if(!RemoveDirectory(tFile))
        result=false;
       else
        result=true;
      }
      else if(!DeleteFile(tFile))
       result=false;
      else
       result=true;

     }while(FindNextFile(hFindFile,&FindFileData));

     FindClose(hFindFile);
}
else
{
     result=false;
}

SetCurrentDirectory(lpBuffer);//回复到原来的目录下

HeapFree(hHeap,HEAP_NO_SERIALIZE,lpBuffer);

return result;
}

// 判断指定的文件夹或文件是否存在。
// isFile为true表示查找对象是文件
BOOL CNTHelper::IsExistFileOrDir(CString szPath, BOOL isFile)
{
BOOL bResult = false;
CFileFind ff;

BOOL res = ff.FindFile(szPath);
while( res )
{
     res = ff.FindNextFile();
     if(ff.IsDirectory() && !isFile) // 文件夹查找
     {
      bResult = true;
     }
     else if (!ff.IsDirectory() && isFile)
     {
      bResult = true;
     }

}
ff.Close();
return bResult;
}

// 判断某个文件或文件夹是否存在(不区分文件还是文件夹)
BOOL CNTHelper::IsExistFileOrDir(CString szPath)
{
BOOL bResult = false;
CFileFind ff;

BOOL res = ff.FindFile(szPath);
while( res )
{
     res = ff.FindNextFile();
     if(ff.IsDirectory())
     {
      bResult = true;     // 文件夹查找
      break;
     }
     else if (!ff.IsDirectory() )
     {
      bResult = true;     // 文件查找
      break;
     }
}
ff.Close();
return bResult;
}

// 创建目录

BOOL CNTHelper::CreateDir(CString szPath )
{
if( IsExistFileOrDir(szPath) ) return TRUE;

HANDLE     fFile;     // File Handle
WIN32_FIND_DATA fileinfo; // File Information Structure
CStringArray m_arr;     // CString Array to hold Directory Structures
BOOL tt;      // BOOL used to test if Create Directory was successful
int x1 = 0;      // Counter
CString tem = _T("");     // Temporary CString Object

fFile = FindFirstFile(szPath,&fileinfo);

// if the file exists and it is a directory
if(fileinfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
     // Directory Exists close file and return
     FindClose(fFile);
     return TRUE;
}

m_arr.RemoveAll();       // Not really necessary - Just habit Separate the String into its compounded components
for(x1 = 0; x1 < szPath.GetLength(); x1++ )     // Parse the supplied CString Directory String
{         
     if(szPath.GetAt(x1) != _T('//') )
      tem += szPath.GetAt(x1);
     else
     {
      m_arr.Add(tem);
      tem += _T("//");
     }
     if(x1 == szPath.GetLength()-1)
      m_arr.Add(tem);
}

// Close the file
FindClose(fFile);

// Now lets cycle through the String Array and create each directory in turn
for(x1 = 1; x1 < m_arr.GetSize(); x1++)
{
     tem = m_arr.GetAt(x1);
     tt = CreateDirectory(tem,NULL);

     // If the Directory exists it will return a false
     if(tt)
      SetFileAttributes(tem,FILE_ATTRIBUTE_NORMAL);
     // If we were successful we set the attributes to normal
}
//     Now lets see if the directory was successfully created
fFile = FindFirstFile(szPath,&fileinfo);

m_arr.RemoveAll();
if(fileinfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
     //     Directory Exists close file and return
     FindClose(fFile);
     return TRUE;
}
else
{
     // For Some reason the Function Failed     Return FALSE
     FindClose(fFile);
     return FALSE;
}

}

 

-时间

CString CNTHelper::GetTimeUUID()
{
CString szUUID;
CTime tt = CTime::GetCurrentTime();
szUUID = tt.Format(_T("%Y%m%d%H%M%S") );
CString szTick;
szTick.Format(_T("%d"),GetTickCount() );
szUUID += szTick;

return szUUID;
}

 

-窗口

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)  
{  
std::vector <HWND> &vtWnd = *(vector<HWND>*)lParam;
vtWnd.push_back(hwnd);

return TRUE;
}

HWND CNTHelper::FindWindowByClassName(LPCTSTR lpClassName)
{
std::vector<HWND> vtWnd;
::EnumWindows(EnumWindowsProc,(long)&vtWnd);

HWND hWnd = NULL;
for(vector<HWND>::iterator iter = vtWnd.begin();iter != vtWnd.end(); iter++)
{
     hWnd =(HWND)*iter;

     if (!::IsWindow(hWnd)) continue;

     //得到ClassName
     TCHAR szClassName[256];
     ::memset(szClassName,sizeof(szClassName),sizeof(TCHAR));
     int nr = ::GetClassName(hWnd, szClassName, 256);

     if(nr == 0)
     {
      continue;
     }

     if (_tcsicmp(szClassName,lpClassName) == 0 )
     {
      return hWnd;
     }
}
return NULL;
}
void CNTHelper::ReallySetForeground( HWND hWnd )
{
DWORD foregroundThreadID;
DWORD ourThreadID;

// If the window is in a minimized state, maximize now
if (::GetWindowLong(hWnd, GWL_STYLE) & WS_MINIMIZE)
{
     ::ShowWindow(hWnd, SW_MAXIMIZE);  
}

// Check to see if we are the foreground thread
foregroundThreadID = GetWindowThreadProcessId(::GetForegroundWindow(),
     NULL);
ourThreadID = ::GetCurrentThreadId();
// If not, attach our thread's 'input' to the foreground thread's
if (foregroundThreadID != ourThreadID)
     AttachThreadInput(foregroundThreadID, ourThreadID, TRUE);
// Bring our window to the foreground
::SetForegroundWindow(hWnd);
// If we attached our thread, detach it now
if (foregroundThreadID != ourThreadID)
     AttachThreadInput(foregroundThreadID, ourThreadID, FALSE);
// Force our window to redraw
//::InvalidateRect(hWnd, NULL, TRUE);
}

 

-结构转换

BOOL CNTHelper::_str2Rect(CString strValue, CRect &rect)
{
CString szTemp;
BOOL bRet = FALSE;
int n = strValue.Find( _T(","));
if( n == -1)
{
     return bRet;
}
else
{
     int i = 0;
     int num[4];
     szTemp = strValue;
     while (i<4 && !szTemp.IsEmpty())
     {
      n = szTemp.Find(_T(","));
      if(n != -1)
      {
       num[i] = _tstoi((LPCTSTR)szTemp.Left(n));
       szTemp = szTemp.Right(szTemp.GetLength() - n -1);
      }
      else if(!szTemp.IsEmpty())
      {
       num[i] = _tstoi((LPCTSTR)szTemp);
       szTemp.Empty();
      }        
      szTemp.TrimLeft();    
      i++;
     }

     if(i == 4)
     {
      //获得rect数值
      rect.SetRect(num[0], num[1], num[2], num[3]);
      bRet = TRUE;
     }
}
return bRet;
}

BOOL CNTHelper::_str2RGB(CString strValue, COLORREF & rgb)
{
CString szTemp;
BOOL bRet = FALSE;
int n = strValue.Find( _T(","));
if( n == -1)
{
     return bRet;
}
else
{
     int i = 0;
     int num[4];
     szTemp = strValue;
     while (i<4 && !szTemp.IsEmpty())
     {
      n = szTemp.Find(_T(","));
      if(n != -1)
      {
       num[i] = _tstoi((LPCTSTR)szTemp.Left(n));
       szTemp = szTemp.Right(szTemp.GetLength() - n -1);
      }
      else if(!szTemp.IsEmpty())
      {
       num[i] = _tstoi((LPCTSTR)szTemp);
       szTemp.Empty();
      }        
      szTemp.TrimLeft();    
      i++;
     }
     if(i == 3 )
     {
      //获得RGB数值
      rgb = RGB(num[0], num[1], num[2]);
      bRet = TRUE;
     }  
}
return bRet;
}

 

-STR GOTO URL

 

///
// GetRegKey
LONG CNTHelper::GetRegKey(HKEY key, LPCTSTR subkey, LPTSTR retdata)
{
HKEY hkey;
LONG retval = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);

if (retval == ERROR_SUCCESS)
{
     long datasize = MAX_PATH;
     TCHAR data[MAX_PATH];
     RegQueryValue(hkey, NULL, data, &datasize);
     _tcscpy(retdata, data);
     RegCloseKey(hkey);
}

return retval;
}


///
// GotoURL
HINSTANCE CNTHelper::GotoURL(LPCTSTR url, int showcmd, BOOL bAlwaysOpenNew /*= FALSE*/)
{
// if no url then this is not an internet link
if (!url || url[0] == _T('/0'))
     return (HINSTANCE) HINSTANCE_ERROR + 1;

TCHAR key[MAX_PATH*2];

//bAlwaysOpenNew = TRUE;
// First try ShellExecute()
TCHAR *verb = _T("open");
if (bAlwaysOpenNew)
     verb = _T("new");
HINSTANCE result = ShellExecute(NULL, verb, url, NULL,NULL, showcmd);

// If it failed, get the .htm regkey and lookup the program
if ((UINT)result <= HINSTANCE_ERROR)
{
     if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS)
     {
      _tcscat(key, _T("//shell//open//command"));

      if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS)
      {
       TCHAR *pos;
       pos = _tcsstr(key, _T("/"%1/""));
       if (pos == NULL)
       {        // No quotes found
        pos = _tcsstr(key, _T("%1")); // Check for %1, without quotes
        if (pos == NULL)       // No parameter at all...
         pos = key + _tcslen(key)-1;
        else
         *pos = _T('/0');       // Remove the parameter
       }
       else
       {
        *pos = _T('/0');        // Remove the parameter
       }

       _tcscat(pos, _T(" "));
       _tcscat(pos, url);

       USES_CONVERSION;
       result = (HINSTANCE) WinExec(T2A(key),showcmd);
      }
     }
}

return result;
}

 

-检测程序是否运行

BOOL CNTHelper::IsAppRun(CString appName)
{
HANDLE handle=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

PROCESSENTRY32* info=new PROCESSENTRY32;
info->dwSize=sizeof(PROCESSENTRY32);
int i=0;
DWORD dwPID;
if(Process32First(handle,info))
{
     if(GetLastError()==ERROR_NO_MORE_FILES )
     {
      CloseHandle(handle);
      return FALSE;
     }
     else
     {
      dwPID = info->th32ProcessID;
   
      if( _tcscmp(info->szExeFile, appName) == 0 )
      {
       CloseHandle(handle);
       return TRUE;
      }

      while(Process32Next(handle,info)!=FALSE)
      {
       dwPID = info->th32ProcessID;
       if( _tcscmp(info->szExeFile, appName) == 0 )
       {
        CloseHandle(handle);
        return TRUE;
       }    

       i++;
      }
     }
}
CloseHandle(handle);
return TRUE;
}

 

-注册 COM 组件

BOOL CNTHelper::RegisterCom(LPCTSTR dllFileName)
{
LPCTSTR      pszDllName      =      dllFileName      ;        //ActiveX控件的路径及文件名       
HINSTANCE      hLib      =      LoadLibrary(pszDllName);      //装载ActiveX控件   
if(hLib < (HINSTANCE)HINSTANCE_ERROR)   
{   
     return      FALSE      ;   
}   
FARPROC      lpDllEntryPoint;     
lpDllEntryPoint      =      GetProcAddress(hLib,_T("DllRegisterServer"));      //获取注册函数DllRegisterServer地址   
if(lpDllEntryPoint!=NULL)          //调用注册函数DllRegisterServer   
{   
     if(FAILED((*lpDllEntryPoint)()))   
     {   
      FreeLibrary(hLib);   
      return      FALSE;   
     }   
     return      TRUE;   
}   
else   
     return      FALSE;   

}

Trackback:http://hi.baidu.com/dd167/blog/item/8394c0dc83319da3cd1166b8.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值