MFC small note: at startup

First, demand

Paper implements MFC program at startup function.

Second, the design

At startup can be achieved through the registry. In Runthe node, a new field, including the program name, the full path. If you want to cancel the automatic start, the field can be deleted.

Third, coding

code show as below:

int SetAutorun(BOOL nEnable)
{
    // 获取程序路径
    CString sPath;
    GetModuleFileName(NULL, sPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
    char lpPath[MAX_PATH] = {0};
    strcpy_s(lpPath, (const char*)sPath.GetBuffer());
    HKEY hkey;
    DWORD dwLen = MAX_PATH;
    int ret = -1;

    // 注意,不能使用HKEY_LOCAL_MACHINE,权限不够
    ret = RegOpenKeyEx(HKEY_CURRENT_USER,
        _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\"),
        0, KEY_WRITE, &hkey);
    if (ret != ERROR_SUCCESS)
    {
        return -1;
    }

    if (nEnable)
    {
        RegSetValueEx(hkey, _T("MyTest"), 0, REG_SZ, (CONST BYTE *)sPath.GetBuffer(), dwLen);

    }
    else
    {
        RegDeleteValue(hkey, _T("MyTest"));
    }

    RegCloseKey(hkey);

    return 0;
}
Published 481 original articles · won praise 244 · Views 1.1 million +

Guess you like

Origin blog.csdn.net/subfate/article/details/103651180