抛砖引玉-VC++常用代码片段

chzuping 2014-03-20 11:19:44
加精

/*
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);

希望大家也一起分享自己的代码片段。
...全文
3260 76 打赏 收藏 转发到动态 举报
写回复
用AI写文章
76 条回复
切换为时间正序
请发表友善的回复…
发表回复
shuzhongxunyu 2014-08-16
  • 打赏
  • 举报
回复
学习下。。。。。
sunnysab 2014-08-16
  • 打赏
  • 举报
回复
GetLocalTime 获得系统时间
dvlinker 2014-08-16
  • 打赏
  • 举报
回复
这些好像都是一些常用的代码段
ANvDbg-Capital 2014-08-03
  • 打赏
  • 举报
回复
MARK...回想当初刚刚参加工作的时候,如果能来这里转一转的话。。。
china_jeffery 2014-05-01
  • 打赏
  • 举报
回复
// 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;
}
lxd1207798 2014-04-29
  • 打赏
  • 举报
回复
这个确实不错~~点赞
鸥翔鱼游1 2014-04-28
  • 打赏
  • 举报
回复
看了此贴菜鸟又涨姿势了
lis2012 2014-04-28
  • 打赏
  • 举报
回复
不错,顶一下
fujialin2011 2014-04-28
  • 打赏
  • 举报
回复
我顶,继续更新
zyjj_99 2014-04-28
  • 打赏
  • 举报
回复
大赞!
洗洗睡去 2014-04-28
  • 打赏
  • 举报
回复
谢谢楼上
不败的拿破仑 2014-04-28
  • 打赏
  • 举报
回复
引用 50 楼 sunnyloves 的回复:
好帖子 再问下 除了codehelp还有什么好的代码仓库软件吗?
以前用mybase不错,当笔记没问题,当代码管理,有时候会乱码。 查了一下,发现CodeLibrary也不错。http://www.orsoon.com/Soft/11835.html
rierrt 2014-04-28
  • 打赏
  • 举报
回复
bin_xiao 2014-04-27
  • 打赏
  • 举报
回复
引用 59 楼 tujiaw 的回复:
编译时间

const TCHAR BuildTime::DATE[] = _T(__DATE__) _T(" at ") _T(__TIME__);
能添加一些用宏连接字串的方法不?不想用_snprintf_s之类的方法去拼接字符串常量。
叶恭介叶恭介 2014-03-30
  • 打赏
  • 举报
回复
忽略看了一下,第二个代码段就有问题了: RegOpenKey...等函数返回值都不加判断 要写成一个个函数才能更好的调用 不过LZ好样的。
xiaojunjun1202 2014-03-28
  • 打赏
  • 举报
回复
好帖!支持下!
kuankuan_qiao 2014-03-26
  • 打赏
  • 举报
回复
ningto.com 2014-03-26
  • 打赏
  • 举报
回复
编译时间

const TCHAR BuildTime::DATE[] = _T(__DATE__) _T(" at ") _T(__TIME__);
uurun 2014-03-26
  • 打赏
  • 举报
回复
h文件

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);
}
uurun 2014-03-26
  • 打赏
  • 举报
回复
class CSection { public: __inline CSection() { InitializeCriticalSection(&m_cs); } __inline ~CSection() { DeleteCriticalSection(&m_cs); } __inline void Lock() { EnterCriticalSection(&m_cs); } __inline void Unlock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; class CSectionGuard { public: __inline CSectionGuard(CSection& cs) : m_cs(cs) { m_cs.Lock(); } __inline ~CSectionGuard() { m_cs.Unlock(); } private: CSection &m_cs; };
加载更多回复(53)

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧