我的DUILIB常用库
生活随笔
收集整理的這篇文章主要介紹了
我的DUILIB常用库
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
頭文件:
#pragma once// // MyLib V1.0 // // 適用字符集: Unicode //#if USE_MFC typedef CString String;#define MYTRACE TRACE #else // DuiLibtypedef CDuiString String;#define MYTRACE DUI__Trace #endifnamespace MyLib {//// 當(dāng)前應(yīng)用程序路徑extern String MODULE_PATH_WITHBS; // 帶反斜杠extern String MODULE_PATH_NOBS; // 不帶反斜杠extern std::string ANSI_MODULE_PATH_WITHBS;extern std::string ANSI_MODULE_PATH_NOBS;//// 初始化應(yīng)用程序路徑變量void InitModulePaths();//// 獲取程序的運(yùn)行完整路徑// 參數(shù):// bBkSlash: 路徑末尾是否加"\", 默認(rèn)不加// module: 程序模塊, 默認(rèn)NULL, 當(dāng)前程序// 返回值:// 完整路徑//String GetModulePath(BOOL bBkSlash = FALSE, HMODULE module = NULL); //// 獲取程序的運(yùn)行完整路徑ANSI// 參數(shù):// bBkSlash: 路徑末尾是否加"\", 默認(rèn)不加// module: 程序模塊, 默認(rèn)NULL, 當(dāng)前程序// 返回值:// 完整路徑ANSI//std::string GetModulePathAnsi(BOOL bBkSlash = FALSE, HMODULE module = NULL); //// 窗口句柄獲取結(jié)構(gòu)體typedef struct tagWNDINFO{DWORD dwProcessId; // 進(jìn)程IDHWND hWnd; // 存放所獲取的句柄 HWND hParWnd; // 父窗口句柄(獲取子窗口句柄)int nType; // 獲取句柄類型String strClass; // 控件類型String strName; // 控件名稱} WNDINFO, *LPWNDINFO;enum {WND_ENUM_VISIBLE = 0, // 窗口可見WND_ENUM_NAME = 1, // 窗口名字完全匹配WND_ENUM_CLASS = 2, // 窗口類型完全匹配WND_ENUM_NAMECLASS = 3, // 窗口名字類型完全匹配WND_ENUM_NAME_LIKE = 4, // 窗口名字部分匹配WND_ENUM_CLASS_LIKE = 5, // 窗口類型部分匹配WND_ENUM_NAMECLASS_LIKE = 6, // 窗口名字類型部分匹配};#define SYMBOL_NOT_FOUND (-1)// // 獲取耗時//// 設(shè)置開始時間 // void BeginTime();//// 設(shè)置結(jié)束時間void EndTime();//// 獲取時間間隔// 返回值:// enum{TIME_IN_MS, // 毫秒TIME_IN_S,};DWORD GetTime(int nType = TIME_IN_MS);//// 根據(jù)程序名字獲取進(jìn)程ID// 參數(shù):// strProcess: 進(jìn)程名, 如process.exe// 返回值:// 成功則返回進(jìn)程ID, 失敗返回-1//DWORD GetProcessIdByName(String strProcess);//// 默認(rèn)窗口遍歷函數(shù)// 參數(shù):// hWnd: EnumWindows/EnumChildWindows 所枚舉得到的窗口句柄// lParam: 傳入的參數(shù)// 返回值:// 窗口不是所需的窗口返回TRUE, 否則返回FALSE//BOOL CALLBACK DefWndEnumProc(HWND hWnd, LPARAM lParam);//// 獲取窗口句柄函數(shù)// 參數(shù):// pWndInfo: 窗口句柄獲取結(jié)構(gòu)體指針// pEnumCallback: 回調(diào)函數(shù), 默認(rèn)為DefWndEnumProc// 返回值:// 成功返回對應(yīng)HWND, 失敗返回NULL//HWND GetProcessHwnd(LPWNDINFO pWndInfo, BOOL (CALLBACK *pEnumCallback)(HWND hWnd,LPARAM lParam) = DefWndEnumProc);//// 如果采用DuiLib, 仿MFC CFileFind的類 #if (!USE_MFC)class CFileFind{public:CFileFind() : m_hFile(INVALID_HANDLE_VALUE) {}BOOL FindFile(String strPath);BOOL FindNextFile();BOOL IsDirectory();BOOL IsDots();String GetFilePath();String GetFileName();void Close();private:String m_strPath;HANDLE m_hFile;WIN32_FIND_DATA m_win32FindData;}; #endif // !USE_MFC//// 字符轉(zhuǎn)換: ANSI, UNICODE //// UTF8的ANSI字符串轉(zhuǎn)換為UNICODE字符串// 參數(shù):// szUtf8: ansi utf8字符串// 返回值:// 轉(zhuǎn)換結(jié)果//String ANSI_to_UTF8(const char* szUtf8);//// ANSI字符串轉(zhuǎn)換為GBK集UNICODE字符串// 參數(shù):// szAnsi: ansi字符串// 返回值:// 轉(zhuǎn)換結(jié)果//String ANSI_to_GBK(const char *szAnsi);//// ANSI字符串轉(zhuǎn)換為UNICODE字符串// 參數(shù):// szAnsi: ansi字符串// 返回值:// 轉(zhuǎn)換后的UNICODE字符串//String ANSI_to_UNICODE(const char * szAnsi);//// UNICODE字符串轉(zhuǎn)換為ANSI字符串// 參數(shù):// strUnicode: UNICODE字符串// 返回值:// 轉(zhuǎn)換后的ansi字符串指針// 備注:// 使用后需要delete指針, 否則內(nèi)存泄漏//char * UNICODE_to_ANSI(String strUnicode);//// UNICODE字符串轉(zhuǎn)換為ANSI字符串// 參數(shù):// strUnicode: UNICODE字符串// strRet: 要存儲的string// 返回值:// 無,解決內(nèi)存泄漏問題//void UNICODE_to_ANSI(String strUnicode, string &strRet);//// ANSI字符串轉(zhuǎn)換為UTF-8 UNICODE字符串// 參數(shù):// szAnsi: ANSI字符串// 返回值:// 轉(zhuǎn)換后的ansi字符串指針// 備注:// 使用后需要delete指針, 否則內(nèi)存泄漏//String Char_To_UTF8(const char *szAnsi);//// 執(zhí)行一條DOS命令// 參數(shù):// strCmd: DOS命令// 返回值:// 執(zhí)行成功TRUE,否則FALSE//BOOL MyCreatePipeProcess(String strCmd);//// 執(zhí)行一條DOS命令并將結(jié)果保存到字符串參數(shù)中// 參數(shù):// strCmd: DOS命令// strResult: 執(zhí)行結(jié)果// 返回值:// 執(zhí)行成功TRUE,否則FALSE//BOOL MyCreatePipeProcess(String strCmd, String &strResult);//// 執(zhí)行一條DOS命令并將結(jié)果寫入文件中// 參數(shù):// strCmd: DOS命令// strResult: 執(zhí)行結(jié)果// 返回值:// 執(zhí)行成功TRUE,否則FALSE//BOOL MyCreatePipeProcessToFile(String strCmd, String strFile);//// 殺死進(jìn)程// 參數(shù):// strExename: exe進(jìn)程名// 返回值:// 無//void KillProcessByName(String strExename);//// 獲取文件長度// 參數(shù):// strPath: 文件絕對路徑// 返回值:// 文件大小(long)//long GetFileSize(String strPath);//// 去除字符串頭尾的空白字符// 參數(shù):// str: 要去除空白字符的字符串// 返回值:// 返回去除空白字符后的字符串String CleanString(String str); }; // namespace MyLib實現(xiàn)文件:
#include "stdafx.h" #include "MyLib.h"#include <TlHelp32.h>// namespace MyLib {// // 當(dāng)前應(yīng)用程序路徑 String MODULE_PATH_WITHBS; // 帶反斜杠 String MODULE_PATH_NOBS; // 不帶反斜杠 std::string ANSI_MODULE_PATH_WITHBS; std::string ANSI_MODULE_PATH_NOBS;// // 時間變量 SYSTEMTIME stBegin; SYSTEMTIME stEnd;String GetModulePath(BOOL bBkSlash /*= FALSE*/, HMODULE module /*= NULL*/) {wchar_t wstrPath[MAX_PATH+1] = {0};DWORD dwRet = ::GetModuleFileNameW(module, wstrPath, MAX_PATH);ASSERT(dwRet > 0); // 返回0代表失敗// 返回如: E:\test\win.exeString strPath(wstrPath);int nPos = strPath.ReverseFind(TEXT('\\'));if (bBkSlash){nPos += 1;}strPath = strPath.Left(nPos);return strPath; }std::string GetModulePathAnsi(BOOL bBkSlash /*= FALSE*/, HMODULE module /*= NULL*/) {char strPath[MAX_PATH] = {0};DWORD dwRet = ::GetModuleFileNameA(module, strPath, MAX_PATH);std::string path(strPath);int nPos = path.find_last_of('\\');if (!bBkSlash){return path.substr(0, nPos);}else{return path.substr(0, nPos+1);} }void InitModulePaths() {MODULE_PATH_WITHBS = GetModulePath(TRUE);MODULE_PATH_NOBS = GetModulePath(FALSE);ANSI_MODULE_PATH_WITHBS = GetModulePathAnsi(TRUE);ANSI_MODULE_PATH_NOBS = GetModulePathAnsi(FALSE); }// // 計算短時耗時, void BeginTime() {GetLocalTime(&stBegin); }void EndTime() {GetLocalTime(&stEnd); }DWORD GetTime(int nType) {DWORD nMilliSecond = 0;nMilliSecond += (stEnd.wHour - stBegin.wHour) * 60 * 60 * 1000;nMilliSecond += (stEnd.wMinute - stBegin.wMinute) * 60 * 1000;nMilliSecond += (stEnd.wSecond - stBegin.wSecond) * 1000;nMilliSecond += (stEnd.wMilliseconds - stBegin.wMilliseconds);if (nType == TIME_IN_S){return (nMilliSecond / 1000);}else{return nMilliSecond;} }DWORD GetProcessIdByName(String strProcess) {HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); // 進(jìn)程快照PROCESSENTRY32 pe;pe.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hSnapShot,&pe)) { return -1; }while (Process32Next(hSnapShot,&pe)) { if(!strProcess.CompareNoCase(pe.szExeFile)) { ::CloseHandle(hSnapShot);return pe.th32ProcessID;} }::CloseHandle(hSnapShot);return -1; }BOOL CALLBACK DefWndEnumProc(HWND hWnd, LPARAM lParam) {DWORD dwProcId;GetWindowThreadProcessId(hWnd, &dwProcId);LPWNDINFO pInfo = (LPWNDINFO)lParam;if (dwProcId == pInfo->dwProcessId){WCHAR wstrTmp1[257] = {0};WCHAR wstrTmp2[257] = {0};GetClassName(hWnd, (LPWSTR)wstrTmp1, 256);GetWindowText(hWnd, (LPWSTR)wstrTmp2, 256);String strClass = wstrTmp1;String strName = wstrTmp2;switch (pInfo->nType){case WND_ENUM_NAME: // 名稱完全匹配if (!strName.CompareNoCase(pInfo->strName)){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_NAME_LIKE: // 名稱部分匹配if (strName.Find(pInfo->strName) != SYMBOL_NOT_FOUND){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_CLASS: // 類型完全匹配if (!strClass.CompareNoCase(pInfo->strClass)){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_CLASS_LIKE: // 類型部分匹配if (strClass.Find(pInfo->strClass) != SYMBOL_NOT_FOUND){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_NAMECLASS: // 名稱類型完全匹配if (!strName.CompareNoCase(pInfo->strName) &&!strClass.CompareNoCase(pInfo->strClass)){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_NAMECLASS_LIKE: // 名稱類型部分匹配if ((strClass.Find(pInfo->strClass) != SYMBOL_NOT_FOUND) &&(strName.Find(pInfo->strName) != SYMBOL_NOT_FOUND)){pInfo->hWnd = hWnd;return FALSE;}break;case WND_ENUM_VISIBLE: // 窗口可見if (IsWindowVisible(hWnd)){pInfo->hWnd = hWnd;return FALSE;}break;default:break;}}return TRUE; }HWND GetProcessHwnd(LPWNDINFO pWndInfo, BOOL (CALLBACK *pEnumCallback)(HWND hWnd,LPARAM lParam)) {pWndInfo->hWnd = NULL;if (pWndInfo->hParWnd == NULL) // 查找父窗口{EnumWindows(pEnumCallback, (LPARAM)pWndInfo);}else // 查找子窗口句柄 {EnumChildWindows(pWndInfo->hParWnd, pEnumCallback, (LPARAM)pWndInfo);}return pWndInfo->hWnd; }// #if (!USE_MFC)BOOL CFileFind::FindNextFile(){if (m_hFile == INVALID_HANDLE_VALUE){return FALSE;}return ::FindNextFileW(m_hFile, &m_win32FindData);}BOOL CFileFind::FindFile(String strPath){int nPos = strPath.ReverseFind(TEXT('\\'));m_strPath = strPath.Left(nPos+1);m_hFile = FindFirstFile(strPath, &m_win32FindData);return (m_hFile != INVALID_HANDLE_VALUE);}BOOL CFileFind::IsDirectory(){return m_win32FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;}BOOL CFileFind::IsDots(){if (m_win32FindData.cFileName[0] == TEXT('.')){return TRUE;}return FALSE;}String CFileFind::GetFileName(){String strFilename;strFilename = m_win32FindData.cFileName;return strFilename;}String CFileFind::GetFilePath(){String strPath;strPath = m_strPath;strPath += m_win32FindData.cFileName;return strPath;}void CFileFind::Close(){if (m_hFile != INVALID_HANDLE_VALUE){FindClose(m_hFile);}} #endif // !USE_MFC //// // 字符串轉(zhuǎn)換 ANSI UNICODEString ANSI_to_UTF8(const char* szUtf8){int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szUtf8, strlen(szUtf8), NULL, 0);wchar_t* wszString = new wchar_t[wcsLen + 1];::MultiByteToWideChar(CP_UTF8, NULL, szUtf8, strlen(szUtf8), wszString, wcsLen);wszString[wcsLen] = TEXT('\0');CDuiString ret = wszString;delete wszString;return ret;}String ANSI_to_GBK(const char *szAnsi){const char* s = szAnsi; int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, s, strlen(s), NULL, 0);wchar_t* pwStr = new wchar_t[wcsLen + 1];::MultiByteToWideChar(CP_UTF8, NULL, s, strlen(s), pwStr, wcsLen);pwStr[wcsLen] = '\0';String strRet(pwStr);delete[] pwStr;return strRet;}String ANSI_to_UNICODE(const char * szAnsi){//ansi 轉(zhuǎn)換為UNICODEint wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), NULL, 0);wchar_t * pwStr = new wchar_t[wcsLen + 1];::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), pwStr, wcsLen);pwStr[wcsLen] = '\0';String strRet(pwStr);delete []pwStr;return strRet;}char * UNICODE_to_ANSI(String strUnicode){int nLen = ::WideCharToMultiByte(CP_ACP, NULL, (LPCWSTR)(strUnicode.GetData()),strUnicode.GetLength(), NULL, 0, NULL, NULL);char *szAnsi = new char [nLen + 1];::WideCharToMultiByte(CP_ACP,NULL, (LPCWSTR)strUnicode.GetData(),strUnicode.GetLength(), szAnsi, nLen, NULL, NULL);szAnsi[nLen] = '\0';return szAnsi;}void UNICODE_to_ANSI(String strUnicode, string &strRet){char *pBuffer = UNICODE_to_ANSI(strUnicode);strRet = pBuffer;delete pBuffer;}String Char_To_UTF8(const char *szAnsi){int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szAnsi, strlen(szAnsi), NULL, 0);wchar_t* wszString = new wchar_t[wcsLen + 1];//轉(zhuǎn)換::MultiByteToWideChar(CP_UTF8, NULL, szAnsi, strlen(szAnsi), wszString, wcsLen);//最后加上'\0'wszString[wcsLen] = '\0';int nLen = WideCharToMultiByte( CP_ACP, 0, wszString, -1, NULL, 0, NULL, NULL );if (nLen == 0){ delete wszString;return _T("");} String str(wszString);delete wszString;return str;} // // 創(chuàng)建進(jìn)程 BOOL MyCreatePipeProcess(String strCmd){String strRslt;return MyCreatePipeProcess(strCmd, strRslt);}BOOL MyCreatePipeProcessToFile(String strCmd, String strFile){String strRslt;BOOL bRet = FALSE;bRet = MyCreatePipeProcess(strCmd, strRslt);if (!bRet){return FALSE;}DeleteFile(strFile);FILE *pFile;_wfopen_s(&pFile, strFile, TEXT("w"));if (pFile == NULL){return FALSE;}char *pBuffer = UNICODE_to_ANSI(strRslt);fwrite(pFile, 1, strlen(pBuffer), pFile);fclose(pFile);delete pBuffer;return TRUE;}BOOL MyCreatePipeProcess(String strCmd, String &strResult){SECURITY_ATTRIBUTES sa;HANDLE hRead, hWrite;std::string result;sa.nLength = sizeof(SECURITY_ATTRIBUTES);sa.lpSecurityDescriptor = NULL;sa.bInheritHandle = TRUE;if (!CreatePipe(&hRead,&hWrite,&sa,0)) {strResult = TEXT("創(chuàng)建管道失敗!");return FALSE;}STARTUPINFO si = {0};si.cb = sizeof(si);si.dwFlags |= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; // 使用默認(rèn)的IO句柄si.hStdOutput = hWrite;si.hStdError = hWrite;si.wShowWindow = SW_HIDE; // 顯示控制臺窗口 PROCESS_INFORMATION pi = {0}; MYTRACE(strCmd);if (!CreateProcess(NULL, (LPWSTR)strCmd.GetData(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { strResult = TEXT("創(chuàng)建進(jìn)程失敗!");return FALSE;}// 線程不再被訪問,關(guān)閉句柄,不影響句柄運(yùn)行CloseHandle(pi.hThread); // 無限期等待線程執(zhí)行完畢// 主線程被掛起WaitForSingleObject(pi.hProcess,INFINITE);DWORD dwExitCode;// 線程結(jié)束,獲取返回碼GetExitCodeProcess(pi.hProcess,&dwExitCode);// 關(guān)閉線程句柄CloseHandle(pi.hProcess);CloseHandle(hWrite);char buffer[257] = {0};DWORD dwBytesRead;strResult = TEXT("");while (ReadFile(hRead, buffer, 256, &dwBytesRead, NULL)){strResult += ANSI_to_UNICODE(buffer);memset(buffer, 0, 256);}MYTRACE(strResult);CloseHandle(hRead);return TRUE;}void KillProcessByName(String strExename){String strCmd;strCmd = TEXT("taskkill /f /im ");strCmd += strExename;strCmd += TEXT(" /t");MyCreatePipeProcess(strCmd);}long GetFileSize(String strPath){FILE *fp;_wfopen_s(&fp, strPath.GetData(), TEXT("rb"));if (fp == NULL){return 0;}fseek(fp, 0, SEEK_END);long lRet = ftell(fp);fclose(fp);return lRet;}String CleanString(String str){if (str.GetLength() < 2){return str;}int eIndex = 0;TCHAR ch = 0;int sIndex = 0;for (int i = 0; i < str.GetLength(); i++){ch = str.GetAt(i);if (ch > 0x20) // 0x20: 空格符號s{sIndex = i;break;}}for (int i = str.GetLength()-1; i >= 0; i--){ch = str.GetAt(i);if (ch > 0x20){eIndex = i;break;}}if (eIndex <= sIndex){return TEXT("XX");}str = str.Mid(sIndex, eIndex-sIndex+1);return str;} }; // namespace MyLib//總結(jié)
以上是生活随笔為你收集整理的我的DUILIB常用库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原来这才是体制内笔杆子干部竞聘演讲稿
- 下一篇: UAP实现拉单代码