c++常用函数封装

头文件:common.h

#pragma once
#pragma warning(disable : 4996)
#include <iostream>
#include <fstream>
#include <bitset>
#include <io.h>
#include <ShlObj.h>
#include <afxcoll.h>
#include<string>
#include <atlstr.h>
#include <vector>
#include <TlHelp32.h>
#include <direct.h>
#include <Windows.h>
using namespace std;
std::string GetFileNameFromPath(std::string path, bool IsShowExtension = false);
std::string GetFileDirFromPath(std::string path);
std::string GetFileExtensionFromPath(std::string path);
bool create_link_file(
	const wchar_t* application,		// 快捷方式对应的程序
	const wchar_t* argvs,				// 传进程序的参数
	const wchar_t* link,					// 快捷方式的路径
	const wchar_t* icon)				// 快捷方式的图标
	;
bool register_shell_extension(
	const wchar_t* reg_type,				// 注册表类型
	const wchar_t* reg_name,			// 注册表名称
	const wchar_t* name,					// 显示名称
	const wchar_t* command,			// 进程路径
	const wchar_t* icon)					// 显示图标
	;
int Wchar2Char(wchar_t* lpwszStrIn, char* pszOut);
int Char2Wchar(wchar_t* wcharStr, const char* charStr);
int CreateDesktopShortcut();
int AddToSystemRun();

void Wchar_tToString(string& szDst, wchar_t* wchar);
DWORD GetProcessidFromName(LPCTSTR name);
char* strstr_rep(char* source, char* old, char* ne);
std::string current_working_directory();
std::vector<std::string> split(std::string str, std::string pattern);
int split(const CString strLine, wchar_t split, CStringArray& strArray);
int get_files(std::string fileFolderPath, std::string fileExtension, std::vector<std::string>& file);
UINT dx_mouse_move(int x = 0, int y = 0, bool IsAbsoluteMove = false);
UINT dx_keyPress(WORD code, int DownTime = 50, int UpTime = 200);
string GetProgramDir();
string GetRegValueString(HKEY hkey, char key[], char name[]);
bool SetRegValueString(HKEY hkey, char key[], char name[], string str);
string& replace_all(string& src, const string& old_value, const string& new_value);
CString gettime();
double GetDistanceForTwoPoint(long x1, long y1, long x2, long y2);
void OutputDebugPrintf(const char* strOutputString, ...);
void OutputDebugStringW2(const std::wstring& str);
void GetWindowSize(HWND hwnd, long* w, long* h);
HMODULE GetProcessModuleHandle(DWORD ProcessId, const WCHAR* szModuleName);
std::string int2BinaryString(int num);
void DoEvents();

源文件:common.cpp

#include "common.h"

std::string GetFileNameFromPath(std::string path, bool IsShowExtension) {
	//取得最后一个路径分隔符的位置
	size_t position = path.find_last_of("/\\");
	if (IsShowExtension == true)
		//截取最后一个路径分隔符后面的字符串即为文件名
		return path.substr(position + 1, path.length() - position - 1);
	size_t position2 = path.find_last_of(".");
	return path.substr(position + 1, position2 - position - 1);
}

std::string GetFileDirFromPath(std::string path) {
	//取得最后一个路径分隔符的位置
	size_t position = path.find_last_of("/\\");
	//截取最后一个路径分隔符后面的字符串即为文件名
	//return path.substr(position + 1, path.length() - position - 1);
	return path.substr(0, position);
}
std::string GetFileExtensionFromPath(std::string path) {
	string filename = GetFileNameFromPath(path);
	//查找最后一个小数点的位置作为扩展名的分隔符
	size_t dot = filename.find_last_of(".");
	//截取小数点之后的字符串即为扩展名
	return filename.substr(dot + 1, filename.length() - dot - 1);
}
bool create_link_file(
	const wchar_t* application,		// 快捷方式对应的程序
	const wchar_t* argvs,				// 传进程序的参数
	const wchar_t* link,					// 快捷方式的路径
	const wchar_t* icon)				// 快捷方式的图标
{
	bool result = false;
	HRESULT hr = CoInitialize(NULL);
	if (SUCCEEDED(hr))
	{
		IShellLink* shell_link = NULL;
		hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&shell_link);
		if (SUCCEEDED(hr))
		{
			// 设置程序路径
			hr = shell_link->SetPath(application);

			wchar_t t[0x100]{ 0 };
			wcscpy_s(t, application);
			wchar_t* p = wcsrchr(t, L'\\');
			p[1] = 0;

			// 设置工作目录
			hr = shell_link->SetWorkingDirectory(t);

			// 设置参数
			hr = shell_link->SetArguments(argvs);

			// 设置图标
			hr = shell_link->SetIconLocation(icon, 0);

			IPersistFile* persist_file = NULL;
			hr = shell_link->QueryInterface(IID_IPersistFile, (void**)&persist_file);
			if (SUCCEEDED(hr))
			{
				// 创建快捷方式
				hr = persist_file->Save((link), FALSE);
				if (SUCCEEDED(hr)) result = true;

				persist_file->Release();
			}
			shell_link->Release();
		}
		CoUninitialize();
	}

	return result;
}
/// <summary>
/// 关联文件类型
/// </summary>
/// <param name="reg_type">注册表类型</param>
/// <param name="reg_name">注册表名称</param>
/// <param name="name">显示名称</param>
/// <param name="command">进程路径</param>
/// <param name="icon">显示图标</param>
/// <returns></returns>
bool register_shell_extension(
	const wchar_t* reg_type,
	const wchar_t* reg_name,
	const wchar_t* name,
	const wchar_t* command,
	const wchar_t* icon)
{
	HKEY key;
	wchar_t path[0x100]{ 0 };

	wsprintfW(path, L"%ws\\shell\\%ws", reg_type, reg_name);
	if (RegCreateKeyW(HKEY_CLASSES_ROOT, path, &key) == ERROR_SUCCESS)
	{
		// 显示的字符串
		RegSetValueExW(key, 0, 0, REG_EXPAND_SZ, (LPBYTE)name, (wcslen(name) + 1) * sizeof(wchar_t));

		// 显示的图标
		RegSetValueExW(key, L"Icon", 0, REG_EXPAND_SZ, (LPBYTE)icon, (wcslen(icon) + 1) * sizeof(wchar_t));
		RegCloseKey(key);
	}

	wsprintfW(path, L"%ws\\shell\\%ws\\Command", reg_type, reg_name);
	if (RegCreateKeyW(HKEY_CLASSES_ROOT, path, &key) == ERROR_SUCCESS)
	{
		// 程序路径
		RegSetValueExW(key, 0, 0, REG_EXPAND_SZ, (LPBYTE)command, (wcslen(command) + 1) * sizeof(wchar_t));
		RegCloseKey(key);
	}

	return true;
}
/******************************************************************************************
Function:        ConvertLPWSTRToLPSTR
Description:     LPWSTR转char*
Input:           lpwszStrIn:待转化的LPWSTR类型
Return:          转化后的char*类型
*******************************************************************************************/
int Wchar2Char(wchar_t* lpwszStrIn, char* pszOut)
{
	int nInputStrLen = 0;
	int nOutputStrLen = 0;
	try
	{
		if (lpwszStrIn != NULL)
		{
			nInputStrLen = wcslen(lpwszStrIn);

			// Double NULL Termination  
			nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
			memset(pszOut, 0x00, nOutputStrLen);
			WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);

		}
	}
	catch (std::exception e)
	{
	}

	return nOutputStrLen;
}
int Char2Wchar(wchar_t* wcharStr, const char* charStr) {
	int len = MultiByteToWideChar(CP_ACP, 0, charStr, strlen(charStr), NULL, 0);

	MultiByteToWideChar(CP_ACP, 0, charStr, strlen(charStr), wcharStr, len);
	wcharStr[len] = '\0';
	return len;
}

/// <summary>
/// 创建桌面快捷方式
/// </summary>
/// <returns></returns>
int CreateDesktopShortcut() {
	char ExePath[1024] = "";
	char filename[1024] = { 0 };
	wchar_t str[520]{ 0 };
	wchar_t wcfilename[520]{ 0 };
	wchar_t wcExePath[520]{ 0 };
	// 创建桌面图标
	wchar_t lpExePath[1024]{ 0 };
	GetModuleFileName(NULL, lpExePath, 1024);
	Wchar2Char(lpExePath, ExePath);
	sprintf_s(filename, 1024, "%s", GetFileNameFromPath(std::string(ExePath)).c_str());
	/*printf("无后缀:%s\r\n", filename);
	printf("有后缀:%s\r\n", GetFileNameFromPath(ExePath, true).c_str());
	printf("程序路径:%s \r\n桌面路径:%s\r\n", ExePath, sDesktopPath);*/
	// 定位桌面路径
	LPITEMIDLIST lp{ 0 };
	HRESULT result = SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp);
	if (SUCCEEDED(result))
	{
		// 转化为字符串
		Char2Wchar(wcfilename, filename);
		if (SHGetPathFromIDListW(lp, str))
		{
			// 创建桌面图标
			wcscat_s(str, L"\\");
			wcscat_s(str, wcfilename);
			wcscat_s(str, L".lnk");
			Char2Wchar(wcExePath, ExePath);
			if (PathFileExists(str))
			{
				char cstr[1024]{ 0 };
				Wchar2Char(str, cstr);
				printf_s("桌面快捷方式已存在:%s\r\n", str);
				return 1;
			}
			if (create_link_file(wcExePath, NULL, str, NULL))
				printf("创建桌面快捷方式成功\r\n");
		}
	}
	return 0;
}
/// <summary>
/// 加到开机启动
/// </summary>
/// <returns></returns>
int AddToSystemRun() {
	TCHAR tcszPath[MAX_PATH]{ 0 };
	char szPath[MAX_PATH]{ 0 };
	char ExePath[1024]{ 0 };
	wchar_t wcExePath[1024]{ 0 };
	char filename[1024] = { 0 };
	char menuPath[1024] = { 0 };
	wchar_t wcmenuPath[1024]{ 0 };
	if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_STARTMENU, NULL, 0, tcszPath)))
	{
		//printf("开始菜单目录:%ls\r\n", &tcszPath);
		GetModuleFileName(NULL, wcExePath, 1024);
		Wchar2Char(wcExePath, ExePath);
		sprintf_s(filename, "%s", GetFileNameFromPath(ExePath).c_str());
		Wchar2Char(tcszPath, szPath);
		strcat_s(menuPath, szPath);
		strcat_s(menuPath, "\\");
		strcat_s(menuPath, filename);
		strcat_s(menuPath, ".lnk");
		//printf("开始菜单路径:%s\r\n", &menuPath);
		Char2Wchar(wcmenuPath, menuPath);
		if (PathFileExists(wcmenuPath))
		{
			printf("开始菜单快捷方式已存在:%s\r\n", &menuPath);
			return 1;
		}
		if (create_link_file(wcExePath, NULL, wcmenuPath, NULL))
		{
			//printf("创建开机启动快捷方式成功\r\n");
			return 1;
		}
	}
	return 0;
}

//--------------------------------------------------------------------------------.
//wchar_t 转 string;
void Wchar_tToString(string& szDst, wchar_t* wchar)
{
	wchar_t* wText = wchar;
	DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);
	char* psText;
	psText = new char[dwNum];
	WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);
	szDst = psText;
	delete[]psText;
}

DWORD GetProcessidFromName(LPCTSTR lpname)
{
	PROCESSENTRY32 pe;
	DWORD id = 0;
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	pe.dwSize = sizeof(PROCESSENTRY32);
	if (!Process32First(hSnapshot, &pe))
		return 0;
	while (1)
	{
		pe.dwSize = sizeof(PROCESSENTRY32);
		if (Process32Next(hSnapshot, &pe) == FALSE)
			break;
		char ExeFile[1024]{ 0 };
		Wchar2Char(pe.szExeFile, ExeFile);
		if (strcmp(ExeFile, (const char*)lpname) == 0)
		{
			id = pe.th32ProcessID;
			break;
		}
	}
	CloseHandle(hSnapshot);
	return id;
}
char* strstr_rep(char* source, char* old, char* ne)//字符替换
{
	char* org = source;
	char temp[256];
	int old_length = strlen(old);//获得将被替换的字符串的大小
	int i, j, k, location = -1;
	for (i = 0; source[i] && (location == -1); ++i)//location查找将被替换的字符串的位置
		for (j = i, k = 0; source[j] == old[k]; j++, k++)
			if (!old[k + 1])
				location = i;
	if (location != -1)//开始替换
	{
		for (j = 0; j < location; j++)//先把被替换的字符串的前一部分COPY到temp
			temp[j] = source[j];
		for (i = 0; ne[i]; i++, j++)//再把替换的新字符串COPY到temp
			temp[j] = ne[i];
		for (k = location + old_length; source[k]; k++, j++)//把剩下的内容COPY到temp
			temp[j] = source[k];
		temp[j] = NULL;
		for (i = 0; source[i] = temp[i]; i++); //把临时字符串temp复制给source
	}
	return org;
}

std::string current_working_directory()
{
	char buff[250];
	_getcwd(buff, 250);
	std::string current_working_directory(buff);
	return current_working_directory;
}
//字符串分割函数
std::vector<std::string> split(std::string str, std::string pattern)
{
	std::string::size_type pos;
	std::vector<std::string> result;
	str += pattern;//扩展字符串以方便操作
	int size = str.size();
	for (int i = 0; i < size; i++)
	{
		pos = str.find(pattern, i);
		if (pos < size)
		{
			std::string s = str.substr(i, pos - i);
			result.push_back(s);
			i = pos + pattern.size() - 1;
		}
	}
	return result;
}
int split(const CString strLine, wchar_t split, CStringArray& strArray)
{
	strArray.RemoveAll();//自带清空属性
	CString temp = strLine;
	int tag = 0;
	while (1)
	{
		tag = temp.Find(split);
		if (tag >= 0)
		{
			strArray.Add(temp.Left(tag));
			temp = temp.Right(temp.GetLength() - tag - 1);
		}
		else { break; }
	}
	strArray.Add(temp);
	return strArray.GetSize();
}


int get_files(std::string fileFolderPath, std::string fileExtension, std::vector<std::string>& file)
{
	std::string fileFolder = fileFolderPath + "\\*" + fileExtension;
	std::string fileName;
	struct _finddata_t fileInfo;
	long long findResult = _findfirst(fileFolder.c_str(), &fileInfo);
	if (findResult == -1)
	{
		_findclose(findResult);
		return 0;
	}
	bool flag = 0;

	do
	{
		//fileName = fileFolderPath + "\\" + fileInfo.name;
		fileName = fileInfo.name;
		if (fileInfo.attrib == _A_ARCH)
		{
			file.push_back(fileName);
		}
	} while (_findnext(findResult, &fileInfo) == 0);

	_findclose(findResult);
}
UINT dx_mouse_move(int x, int y, bool IsAbsoluteMove)
{
	INPUT input;
	input.type = INPUT_MOUSE;
	input.mi.mouseData = 0;
	input.mi.time = 0;
	if (IsAbsoluteMove) {
		int sx = GetSystemMetrics(SM_CXSCREEN);
		int sy = GetSystemMetrics(SM_CYSCREEN);
		input.mi.dx = x * 65535 / (sx - 1);
		input.mi.dy = y * 65535 / (sy - 1);
		input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
	}
	else {
		input.mi.dx = x;
		input.mi.dy = y;
		input.mi.dwFlags = MOUSEEVENTF_MOVE;
	}
	return SendInput(1, &input, sizeof(input));
}
UINT dx_keyPress(WORD code, int DownTime, int UpTime) {
	INPUT input;
	input.ki.wVk = code; // virtual-key code for the key
	input.ki.dwFlags = 0;
	input.ki.time = 0;
	SendInput(1, &input, sizeof(INPUT));
	Sleep(DownTime);
	input.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
	UINT result = SendInput(1, &input, sizeof(INPUT));
	Sleep(UpTime);
	return result;
};
string GetProgramDir()
{
	char exeFullPath[MAX_PATH]; // Full path 
	string strPath = "";
	wchar_t wcexeFullPath[11024]{ 0 };
	Char2Wchar(wcexeFullPath, exeFullPath);
	GetModuleFileName(NULL, wcexeFullPath, MAX_PATH);
	strPath = (string)exeFullPath;    // Get full path of the file
	int pos = strPath.find_last_of('\\', strPath.length());
	return strPath.substr(0, pos);  // Return the directory without the file name 
}
string GetRegValueString(HKEY hkey, char key[], char name[])
{
	HKEY hOpen;
	char buf[255]{ 0 };
	DWORD size;
	string str = "";
	wchar_t wcbuf[255]{ 0 };
	Char2Wchar(wcbuf, buf);
	if (ERROR_SUCCESS == RegOpenKeyEx(hkey, wcbuf, 0, KEY_READ, &hOpen))
	{
		RegQueryValueExA(hOpen, name, NULL, NULL, (BYTE*)buf, &size);
		str = string(buf);
	}
	RegCloseKey(hOpen);
	return str;
}
bool SetRegValueString(HKEY hkey, char key[], char name[], string str)
{
	HKEY hOpen;

	if (ERROR_SUCCESS == RegCreateKeyA(hkey, key, &hOpen))
	{
		RegSetValueExA(hOpen, name, 0, REG_SZ, (unsigned char*)(unsigned char*)str.c_str(), lstrlenA(str.c_str()));
		RegCloseKey(hOpen);
		return true;
	}
	return false;
}
/*
 * string& replace_all (string& src, const string& old_value, const string& new_value);
 * 参数:源字符串src    被替换的子串old_value    替换的子串new_value
 *
 * 功能:将 源串src 中 子串old_value 全部被替换为 new_value
 */
string& replace_all(string& src, const string& old_value, const string& new_value) {
	// 每次重新定位起始位置,防止上轮替换后的字符串形成新的old_value
	for (string::size_type pos(0); pos != string::npos; pos += new_value.length()) {
		if ((pos = src.find(old_value, pos)) != string::npos) {
			src.replace(pos, old_value.length(), new_value);
		}
		else break;
	}
	return src;
}
CString gettime()
{
	time_t rawtime;
	struct tm* ptminfo;
	time(&rawtime);
	ptminfo = localtime(&rawtime);
	CString str;
	str.Format(_T("%02d-%02d-%02d %02d:%02d:%02d "), ptminfo->tm_year + 1900, ptminfo->tm_mon + 1, ptminfo->tm_mday, ptminfo->tm_hour, ptminfo->tm_min, ptminfo->tm_sec);
	return str;
}

double GetDistanceForTwoPoint(long x1, long y1, long x2, long y2) {
	long a = abs(x1 - x2);
	long b = abs(y1 - y2);
	return sqrt(a * a + b * b);
}
void OutputDebugPrintf(const char* strOutputString, ...)
{
	char strBuffer[4096] = { 0 };
	try {
		va_list vlArgs;
		va_start(vlArgs, strOutputString);
		_vsnprintf_s(strBuffer, sizeof(strBuffer) - 1, strOutputString, vlArgs);
		//vsprintf(strBuffer, strOutputString, vlArgs);
		va_end(vlArgs);
		strcat(strBuffer, "\r\n");
		OutputDebugString(CA2W(strBuffer));
		//daily_file_logger->debug(strBuffer);
	}
	catch (exception err) {
		sprintf_s(strBuffer, sizeof(err), "%s", err);
		OutputDebugString(CA2W(strBuffer));
		//cout << strOutputString << str << endl;
	}
}
void OutputDebugStringW2(const std::wstring& str) {
	int size = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr);
	std::string ansi_str;
	ansi_str.resize(size);
	WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, &ansi_str[0], size, nullptr, nullptr);
	OutputDebugStringA(ansi_str.c_str());
}
void GetWindowSize(HWND hwnd, long* w, long* h)
{
	RECT rect;
	GetWindowRect(hwnd, &rect);
	*w = rect.right - rect.left;
	*h = rect.bottom - rect.top;
}
HMODULE GetProcessModuleHandle(DWORD ProcessId, const WCHAR* szModuleName)
{
	MODULEENTRY32 moduleEntry;
	HANDLE hSnapshot = NULL;

	hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);

	if (!hSnapshot)
	{
		if (hSnapshot != NULL) ::CloseHandle(hSnapshot);
		return NULL;
	}

	ZeroMemory(&moduleEntry, sizeof(MODULEENTRY32));
	moduleEntry.dwSize = sizeof(MODULEENTRY32);

	if (!Module32First(hSnapshot, &moduleEntry))
	{
		::CloseHandle(hSnapshot);
		return NULL;
	}

	do {
		if (wcscmp((const wchar_t*)moduleEntry.szModule, szModuleName) == NULL) return moduleEntry.hModule;
	} while (Module32Next(hSnapshot, &moduleEntry));

	::CloseHandle(hSnapshot);
	return NULL;
}
/// <summary>
/// 整数到二进制字符串
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
std::string int2BinaryString(int num) {
	std::bitset<32> binary(num);
	return binary.to_string();
}
void DoEvents()
{
	MSG msg;
	while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}

目前源码功能完善中,不足之处,在所难免,如有疏忽,欢迎联系我进行更正。更多功能,欢迎投稿,,关注后期更新,不定期更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值