16,472
社区成员
发帖
与我相关
我的任务
分享
/*
1.改变当前目录到EXE所在的目录
在VC++开发环境中直接运行程序,当前目录不是EXE所在的目录,这样会造成一些麻烦,比如使用相对路径打开文件。使用以下代码将当前目录设成EXE所在的目录:
void ChangeCurDirToExe()
{
CString strPath;
::GetModuleFileName(NULL,strPath.GetBuffer(MAX_PATH),MAX_PATH);
strPath.ReleaseBuffer();
strPath = strPath.Left(strPath.ReverseFind(L'\\') +1 );
::SetCurrentDirectory(strPath.GetBuffer());
}
/*2.开机自运行*/
HKEY m_regkey;
TCHAR filename[_MAX_PATH];
GetModuleFileName(NULL,filename,_MAX_PATH);
RegOpenKey(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&m_regkey);
RegSetValueEx(m_regkey,L"程序名称",0,REG_SZ,(const unsigned char *)filename,MAX_PATH);
RegCloseKey(m_regkey);
/*3.取消开机自运行*/
HKEY hKey;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_ALL_ACCESS,&hKey)==ERROR_SUCCESS)
{
RegDeleteValue(hKey,L"程序名称");
RegCloseKey(hKey);
}
/*4.退出后重启*/
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, MAX_PATH);
STARTUPINFO startupInfo;
PROCESS_INFORMATION procInfo;
memset(&startupInfo,0x00,sizeof(STARTUPINFO));
startupInfo.cb = sizeof(STARTUPINFO);
::CreateProcess(szPath,NULL,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,NULL,&startupInfo,&procInfo);
/*5.只运行一个实例*/
HANDLE m_hMutex = CreateMutex(NULL, FALSE, _T("AetasServer"));
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
AfxMessageBox(L"程序名称,已经运行");
CloseHandle(m_hMutex);
m_hMutex = NULL;
return FALSE;
}
/*6.链接到库文件*/
#pragma comment(lib, "winspool.lib")
/*7.在窗口程序中输出信息到控制台*/
#include <io.h>
#include <fcntl.h>
void InitConsole()
{
int nRet= 0;
FILE* fp;
AllocConsole();
nRet= _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
fp = _fdopen(nRet, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
}
//程序退出时调用
FreeConsole(VOID);
// Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0)
return "";
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
const TCHAR BuildTime::DATE[] = _T(__DATE__) _T(" at ") _T(__TIME__);
class CHelper
{
public:
static tstring GetModulePath(TCHAR* filename = NULL);
static tstring GetModuleName();
static HMODULE LoadDll(TCHAR* name, bool bWarn = true/*加载失败是否提示*/);
static string& TrimLeft(string& str, char ch);
static string& TrimRight(string& str, char ch);
static string& Trim(string& str, char ch);
static vector<string> Split(string& str, char ch);
static bool Utf2Unicode(string& utf8, wstring& unicode);
static bool Unicode2Ascii(wstring& unicode, string& ascii);
static bool Utf2Ascii(string &utf, string &ascii);
static bool Ascii2Unicode(string& ascii, wstring& unicode);
static bool Unicode2Utf(wstring &unicode, string &utf);
static bool Ascii2Utf(string &ascii, string &utf);
static bool IsNumber(const char *str);
static bool IsIpAddress(const char *ipstr);
};
cpp文件
#include <windows.h>
#include "Helper.h"
#include <regex>
#include <algorithm>
tstring CHelper::GetModulePath(TCHAR *fileName)
{
TCHAR cpath[MAX_PATH + 1] = {0};
HMODULE hModule;
void *callerAddress = _ReturnAddress();
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &hModule);
GetModuleFileName(hModule, cpath, sizeof(cpath)/sizeof(TCHAR));
tstring spath = cpath;
int pos = spath.find_last_of('\\');
spath = spath.substr(0, pos + 1);
return fileName == NULL? spath: spath + fileName;
}
tstring CHelper::GetModuleName()
{
TCHAR cpath[MAX_PATH + 1] = {0};
HMODULE hModule;
void *callerAddress = _ReturnAddress();
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &hModule);
GetModuleFileName(hModule, cpath, sizeof(cpath)/(sizeof(TCHAR)));
tstring spath = cpath;
int pos = spath.find_last_of('\\');
spath = spath.substr(pos + 1);
return spath;
}
HMODULE CHelper::LoadDll(TCHAR* name, bool bWarn)
{
HMODULE hDll = ::LoadLibrary(GetModulePath(name).c_str());
if (hDll == NULL && bWarn)
{
tstring msg = _T("加载Dll “") + GetModulePath(name) + _T("” 失败,请检查该文件是否存在!");
::MessageBox(NULL, msg.c_str(), _T("加载Dll失败"), MB_OK);
}
return hDll;
}
string& CHelper::TrimLeft(string& str, char ch)
{
int pos = 0;
for (pos = 0; pos < (int)str.size(); pos++)
{
if (str.at(pos) != ch) break;
}
str = str.substr(pos);
return str;
}
string& CHelper::TrimRight(string& str, char ch)
{
vector<char> chs;
int pos = str.size() - 1;
for (pos; pos >= 0; pos--)
{
if (str.at(pos) != ch) break;
}
str.resize(pos + 1);
return str;
}
string& CHelper::Trim(string& str, char ch)
{
return TrimLeft(TrimRight(str, ch), ch);
}
vector<string> CHelper::Split(string& str, char ch)
{
vector<string> sp_strs;
Trim(str, ch);
string::size_type s_p = 0, e_p = 0;
while (e_p != string::npos && e_p != str.length())
{
e_p = str.find_first_of(ch, s_p);
if (e_p == string::npos) e_p = str.length();
sp_strs.push_back(str.substr(s_p, e_p - s_p));
s_p = e_p + 1;
}
return sp_strs;
}
bool CHelper::Utf2Unicode(string& utf8, wstring& unicode)
{
int wideSize = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
if (wideSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (wideSize == 0)
return false;
vector<wchar_t> resultString(wideSize);
int convResult = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &resultString[0], wideSize);
if (convResult != wideSize)
return false;
unicode = wstring(&resultString[0]);
return true;
}
bool CHelper::Unicode2Ascii(wstring& unicode, string& ascii)
{
int asciiSize = ::WideCharToMultiByte(CP_OEMCP, 0, unicode.c_str(), -1, NULL, 0, NULL, NULL);
if (asciiSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (asciiSize == 0)
return false;
vector<char> resultString(asciiSize);
int convResult = ::WideCharToMultiByte(CP_OEMCP, 0, unicode.c_str(), -1, &resultString[0], asciiSize, NULL, NULL);
if (convResult != asciiSize) return false;
ascii = string(&resultString[0]);
return true;
}
bool CHelper::Utf2Ascii(string &utf, string &ascii)
{
wstring wstr;
bool res;
res = Utf2Unicode(utf, wstr);
if (!res) return false;
res = Unicode2Ascii(wstr, ascii);
if (!res) return false;
return true;
}
bool CHelper::Ascii2Unicode(string& ascii, wstring& unicode)
{
int wideSize = MultiByteToWideChar(CP_ACP, 0, (char *)ascii.c_str(), -1, NULL, 0);
if (wideSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (wideSize == 0)
return false;
vector<wchar_t> resultString(wideSize);
int conResult = MultiByteToWideChar(CP_ACP, 0, (char *)ascii.c_str(), -1, &resultString[0], wideSize);
if (conResult != wideSize)
return false;
unicode = wstring(&resultString[0]);
return true;
}
bool CHelper::Unicode2Utf(wstring &unicode, string &utf)
{
int utfSize = WideCharToMultiByte(CP_UTF8, 0, unicode.c_str(), -1, NULL, 0, NULL, NULL);
if (utfSize == 0)
return false;
vector<char> resultString(utfSize);
int conResult = WideCharToMultiByte(CP_UTF8, 0, unicode.c_str(), -1, &resultString[0], utfSize, NULL, NULL);
if (conResult == utfSize)
return false;
utf = string(&resultString[0]);
return true;
}
bool CHelper::Ascii2Utf(string &ascii, string &utf)
{
wstring unicode;
bool res;
res = Ascii2Unicode(ascii, unicode);
if (res == false) return false;
res = Unicode2Utf(unicode, utf);
if (res == false) return false;
return true;
}
bool CHelper::IsNumber(const char *str)
{
if (str == NULL) return false;
while (*str++ != '\0')
{
if (*str < '0' || *str > '9') return false;
}
return true;
}
bool CHelper::IsIpAddress(const char *ipstr)
{
if (ipstr == NULL) return false;
regex ipPattern("(\\d{1,3}.){3}(\\d{1,3})");
return regex_match(ipstr, ipPattern);
}