分类目录归档:VC++

VC HttpClient

HttpClient.h

#pragma once
#include <string>
#include <vector>
using namespace std;

class CHttpClient
{
public:
	CHttpClient(void);
	~CHttpClient(void);

	BOOL Get(LPCSTR url, string &result);
};

HttpClient.cpp

#include "stdafx.h"
#include "HttpClient.h"
#include <wininet.h>   
#pragma comment(lib, "wininet.lib") 


CHttpClient::CHttpClient(void)
{
}

CHttpClient::~CHttpClient(void)
{
}


BOOL CHttpClient::Get(LPCSTR url, string &result)
{
	result.clear();

	vector<char> v; 
	const CHAR * szUrl = url; 
	CHAR szAgent[] = ""; 
	HINTERNET hInternet1 =  
		InternetOpen(NULL,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,NULL); 
	if (NULL == hInternet1) 
	{ 
		InternetCloseHandle(hInternet1); 
		return FALSE; 
	} 
	HINTERNET hInternet2 =  
		InternetOpenUrl(hInternet1,szUrl,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE,NULL); 
	if (NULL == hInternet2) 
	{ 
		InternetCloseHandle(hInternet2); 
		InternetCloseHandle(hInternet1); 
		return FALSE; 
	} 
	DWORD dwMaxDataLength = 500; 
	PBYTE pBuf = (PBYTE)malloc(dwMaxDataLength*sizeof(TCHAR)); 
	if (NULL == pBuf) 
	{ 
		InternetCloseHandle(hInternet2); 
		InternetCloseHandle(hInternet1); 
		return FALSE; 
	} 
	DWORD dwReadDataLength = NULL; 
	BOOL bRet = TRUE; 
	do  
	{ 
		ZeroMemory(pBuf,dwMaxDataLength*sizeof(TCHAR)); 
		bRet = InternetReadFile(hInternet2,pBuf,dwMaxDataLength,&dwReadDataLength); 
		for (DWORD dw = 0;dw < dwReadDataLength;dw++) 
		{ 
			v.push_back(pBuf[dw]); 
		} 
	} while (NULL != dwReadDataLength); 

	vector<char>::iterator i; 
	for(i=v.begin(); i!=v.end(); i++) 
		result += *i;

	return TRUE;
}

VC获取进程加载的DLL模块

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS// and compile with -DPSAPI_VERSION=1

int PrintModules(DWORD processID)
{
    HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    // Print the process identifier.

    printf("\nProcess ID: %u\n", processID);

    // Get a handle to the process.

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
                               PROCESS_VM_READ,
                           FALSE, processID);
    if (NULL == hProcess)
        return 1;

    // Get a list of all the modules in this process.

    if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
    {
        for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
        {
            TCHAR szModName[MAX_PATH];

            // Get the full path to the module's file.

            if (GetModuleFileNameEx(hProcess, hMods[i], szModName,
                                    sizeof(szModName) / sizeof(TCHAR)))
            {
                // Print the module name and handle value.

                _tprintf(TEXT("\t%s (0x%08X)\n"), szModName, hMods[i]);
            }
        }
    }

    // Release the handle to the process.

    CloseHandle(hProcess);

    return 0;
}

int main(void)
{

    DWORD aProcesses[1024];
    DWORD cbNeeded;
    DWORD cProcesses;
    unsigned int i;

    // Get the list of process identifiers.

    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
        return 1;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the names of the modules for each process.

    for (i = 0; i < cProcesses; i++)
    {
        PrintModules(aProcesses[i]);
    }

    return 0;
}

VC++开机启动

inline void SetAutoRun()
{
       TCHAR szFilePath[MAX_PATH];
       memset(szFilePath, 0, MAX_PATH);
       if (GetModuleFileName(NULL, szFilePath, MAX_PATH))
       {
              HKEY hKey;
              CString strRegPath = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
              if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, strRegPath, 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
              {
                     RegSetValueEx(hKey, _T("SecContrl"), 0, REG_SZ, (LPBYTE)szFilePath, (lstrlen(szFilePath) + 1)*sizeof(TCHAR));
              }
              RegCloseKey(hKey);
       }
}
inline void ReSetAutoRun()
{
       HKEY hKey;
       CString strRegPath = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
       if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, strRegPath, 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
       {
              RegDeleteValue(hKey, _T("SecContrl"));
       }
       RegCloseKey(hKey);
}

MFC 打印图片

BOOL PrintBitmap(LPCTSTR filename)
{
    CPrintDialog printDlg(FALSE);
    // printDlg.GetDefaults();

    if (printDlg.DoModal() == IDCANCEL)
        return FALSE;

    CDC dc;
    if (!dc.Attach(printDlg.GetPrinterDC()))
    {
        AfxMessageBox(_T("未发现发打印设备"));
        return FALSE;
    }

    dc.m_bPrinting = TRUE;
    DOCINFO di;
    // 初始化打印信息
    ::ZeroMemory(&di, sizeof(DOCINFO));
    di.cbSize = sizeof(DOCINFO);
    di.lpszDocName = filename;
    BOOL bPrintingOK = dc.StartDoc(&di); // 开始打印

    CPrintInfo Info;
    Info.SetMaxPage(1); // 只打印一页
    int maxw = dc.GetDeviceCaps(HORZRES);
    int maxh = dc.GetDeviceCaps(VERTRES);
    Info.m_rectDraw.SetRect(0, 0, maxw, maxh);
    for (UINT page = Info.GetMinPage(); page <=Info.GetMaxPage() && bPrintingOK; page++)
    {
        dc.StartPage(); // 开始打印新的一页
        Info.m_nCurPage = page;
        CBitmap bitmap;

        // 加载位图
        if (!bitmap.Attach(::LoadImage(::GetModuleHandle(NULL), filename, IMAGE_BITMAP, 0, 0,LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE)))
        {
            AfxMessageBox(_T("位图加载失败!"));
            return FALSE;
        }
        BITMAP bm;
        bitmap.GetBitmap(&bm);
        int w = bm.bmWidth;
        int h = bm.bmHeight;
        // 创建内存设备上下文
        CDC memDC;
        memDC.CreateCompatibleDC(&dc);
        CBitmap *pBmp = memDC.SelectObject(&bitmap);
        memDC.SetMapMode(dc.GetMapMode());
        dc.SetStretchBltMode(HALFTONE);
        // 拉伸打印
        dc.StretchBlt(0, 0, maxw, maxh, &memDC, 0, 0, w, h, SRCCOPY);
        // clean up
        memDC.SelectObject(pBmp);
        // end page
        bPrintingOK = (dc.EndPage() > 0);
    }
    if (bPrintingOK)
        dc.EndDoc(); // 打印完成
    else

        dc.AbortDoc(); // 终止打印

    return TRUE;
}

void CPrintDemoDlg::OnBnClickedOk()
{
    BOOL bRet = PrintBitmap(_T("1.bmp"));

    if (bRet)
        AfxMessageBox(_T("打印完成"));
}

VC生成隐藏 受保护的系统目录 

/*  add by laowu 20160904   */
TCHAR szPath[MAX_PATH];
ZeroMemory(szPath, MAX_PATH);
SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE);
strcat(szPath, "\\Winsys");

if (!PathIsDirectory(szPath))
{
       ::CreateDirectory(szPath, NULL);
       SetFileAttributes(szPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM );  // 主要是这句,设置文件夹的属性
}

vc常用到的一些函数 

#include <Shlwapi.h>
#pragma comment (lib , "shlwapi.lib" )

#define nullptr NULL

inline BYTE toHex(const BYTE &x)
{
       return x > 9 ? x + 55: x + 48;
}

inline CString UrlEncode(CString sIn)
{
       CString sOut;
       const int nLen = sIn.GetLength() + 1;
       register LPBYTE pOutTmp = NULL;
       LPBYTE pOutBuf = NULL;
       register LPBYTE pInTmp = NULL;
       LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
       BYTE b = 0;

       //alloc out buffer
       pOutBuf = (LPBYTE)sOut.GetBuffer(nLen*3 - 2);//new BYTE [nLen * 3];

       if(pOutBuf)
       {
              pInTmp = pInBuf;
              pOutTmp = pOutBuf;

              // do encoding
              while (*pInTmp)
              {
                     if(isalnum(*pInTmp))
                           *pOutTmp++ = *pInTmp;
                     else
                           if(isspace(*pInTmp))
                                  *pOutTmp++ = '+';
                           else
                           {
                                  *pOutTmp++ = '%';
                                  *pOutTmp++ = toHex(*pInTmp>>4);
                                  *pOutTmp++ = toHex(*pInTmp%16);
                           }
                           pInTmp++;
              }
              *pOutTmp = '\0';
              //sOut=pOutBuf;
              //delete [] pOutBuf;
              sOut.ReleaseBuffer();
       }
       sIn.ReleaseBuffer();
       return sOut;
}

inline int SplitString(CString & str, TCHAR cTok, CStringArray& aryItem)
{
       TCHAR* p = str.GetBuffer(0);
       TCHAR* e = p;
       TCHAR cEnd = *e;
       int nCount = 0;
       while (cEnd)
       {
              if (*e == _T('\0'))
                     cEnd = *e;
              else if (*e == cTok)
                     *e = _T('\0');

              if (*e)
                     e++;
              else
              {
                     if (*p != _T('\0'))
                     {
                           aryItem.Add(p);
                           nCount++;
                     }
                     p = ++e;
              }
       }
       return nCount;
}

inline void MakeSureCreateDir(CString basePath, CString path)
{
       CStringArray arr;
       SplitString(path, '\\', arr);
       for (int i = 0; i < arr.GetCount(); i++)
       {
              basePath += L"\\" + arr[i];

              if (!PathFileExists(basePath))
                     ::CreateDirectory(basePath, NULL);
       }
}

VC创建快捷方式

//得到当前桌面路径
BOOL GetDesktopPath(TCHAR * pszDesktopPath)
{
                 LPITEMIDLIST   ppidl = NULL ;
                 if (SHGetSpecialFolderLocation(NULL , CSIDL_DESKTOP, &ppidl) == S_OK )
                {
                                 BOOL flag = SHGetPathFromIDList (ppidl, pszDesktopPath);
                                CoTaskMemFree(ppidl);
                                 return flag;
                }
                 return FALSE ;
}

//得到快速启动栏的路径
BOOL GetIEQuickLaunchPath(TCHAR * pszIEQueickLaunchPath)
{
                 LPITEMIDLIST   ppidl;
                 if (SHGetSpecialFolderLocation(NULL , CSIDL_APPDATA, &ppidl) == S_OK )
                {
                                 BOOL flag = SHGetPathFromIDList (ppidl, pszIEQueickLaunchPath);
                                 lstrcat (pszIEQueickLaunchPath , _T( "\\Microsoft\\Internet Explorer\\Quick Launch" ));
                                CoTaskMemFree(ppidl);
                                 return flag;
                }
                 return FALSE ;
}

//得到 开始->程序组 的路径
BOOL GetProgramsPath(TCHAR * pszProgramsPath)
{
                 LPITEMIDLIST   ppidl;
                 if (SHGetSpecialFolderLocation(NULL , CSIDL_PROGRAMS, &ppidl) == S_OK )
                {
                                 BOOL flag = SHGetPathFromIDList (ppidl, pszProgramsPath);
                                CoTaskMemFree(ppidl);
                                 return flag;
                }
                 return FALSE ;
}

/*
函数功能:对指定文件在指定的目录下创建其快捷方式
函数参数:
lpszFileName    指定文件,为NULL表示当前进程的EXE文件。
lpszLnkFileDir  指定目录,不能为NULL。
lpszLnkFileName 快捷方式名称,为NULL表示EXE文件名。
wHotkey         为0表示不设置快捷键
pszDescription  备注
iShowCmd        运行方式,默认为常规窗口
*/

BOOL CreateFileShortcut(LPCTSTR lpszFileName, LPCTSTR lpszLnkFileDir , LPCTSTR lpszLnkFileName , LPCTSTR lpszWorkDir , WORD wHotkey, LPCTSTR lpszDescription , int iShowCmd = SW_SHOWNORMAL )
{
                 if (lpszLnkFileDir == NULL)
                                 return FALSE ;

                 HRESULT hr;
                 IShellLink      *pLink;  //IShellLink对象指针
                 IPersistFile    *ppf; //IPersisFil对象指针

                 //创建IShellLink对象
                hr = CoCreateInstance(CLSID_ShellLink, NULL , CLSCTX_INPROC_SERVER , IID_IShellLink, (void **)&pLink);
                 if (FAILED (hr))
                                 return FALSE ;

                 //从IShellLink对象中获取IPersistFile接口
                hr = pLink->QueryInterface(IID_IPersistFile, ( void **)&ppf);
                 if (FAILED (hr))
                {
                                pLink->Release();
                                 return FALSE ;
                }

                 //目标
                 if (lpszFileName == NULL)
                                pLink->SetPath( _wpgmptr );
                 else
                                pLink->SetPath( lpszFileName );

                 //工作目录
                 if (lpszWorkDir != NULL)
                {
                                 //pLink->SetPath(lpszWorkDir);

                                pLink->SetWorkingDirectory( lpszWorkDir );
                }

                 //快捷键
                 if (wHotkey != 0)
                                pLink->SetHotkey( wHotkey );

                 //备注
                 if (lpszDescription != NULL)
                                pLink->SetDescription( lpszDescription );

                 //显示方式
                pLink->SetShowCmd( iShowCmd );

                 //快捷方式的路径 + 名称
                 TCHAR szBuffer[MAX_PATH ];
                 if (lpszLnkFileName != NULL) //指定了快捷方式的名称
                                 wsprintf (szBuffer, _T ( "%s\\%s"), lpszLnkFileDir , lpszLnkFileName );
                 else
                {
                                 //没有指定名称,就从取指定文件的文件名作为快捷方式名称。
                                 TCHAR *pstr;
                                 if (lpszFileName != NULL)
                                                pstr = (TCHAR *)wcsrchr(lpszFileName , _T( '\\'));
                                 else
                                                pstr = (TCHAR *)wcsrchr(_wpgmptr , _T( '\\'));

                                 if (pstr == NULL )
                                {
                                                ppf->Release();
                                                pLink->Release();
                                                 return FALSE ;
                                }

                                 //注意后缀名要从.exe改为.lnk
                                 wsprintf (szBuffer, _T ( "%s\\%s"), lpszLnkFileDir , pstr);
                                 int nLen = lstrlen (szBuffer);
                                szBuffer[nLen - 3] = 'l' ;
                                szBuffer[nLen - 2] = 'n' ;
                                szBuffer[nLen - 1] = 'k' ;
                }

                 //保存快捷方式到指定目录下

                 //WCHAR  wsz[MAX_PATH];  //定义Unicode字符串

                 //MultiByteToWideChar(CP_ACP, 0, szBuffer, -1, wsz, MAX_PATH);

                hr = ppf->Save(szBuffer, TRUE );

                ppf->Release();
                pLink->Release();
                 return SUCCEEDED (hr);

}

调用

TCHAR wszModulePath[MAX_PATH ];
::memset(wszModulePath, 0, sizeof (TCHAR )* MAX_PATH);
GetModuleFileName (NULL , wszModulePath, MAX_PATH);
PathAppend (wszModulePath, _T ( "..\\"));
wcscat_s(wszModulePath, _T ("3D绘图宝.exe" ));

TCHAR wszModulePath2[MAX_PATH ];
::memset(wszModulePath2, 0, sizeof (TCHAR )* MAX_PATH);
GetModuleFileName (NULL , wszModulePath2, MAX_PATH);
PathAppend (wszModulePath2, _T ( "..\\"));

TCHAR   szPath[MAX_PATH ];
CoInitialize( NULL );

GetProgramsPath(szPath);
if (CreateFileShortcut(wszModulePath, szPath, NULL, wszModulePath2, MAKEWORD (VK_F12 , HOTKEYF_CONTROL ), _T ( "")))
{

}

memset(szPath, 0, sizeof (TCHAR )* MAX_PATH);

GetDesktopPath(szPath);
if (CreateFileShortcut(wszModulePath, szPath, NULL, wszModulePath2, MAKEWORD (VK_F12 , HOTKEYF_CONTROL ), _T ( "")))
{
        AfxMessageBox( _T ("软件安装成功欢迎使用。" ));
}


CoUninitialize();

VC 获取软件安装列表

#include <comdef.h>

#include <wbemidl.h>

#pragma comment ( lib, "wbemuuid.lib")
#include <string>
using namespace std;


void CdeltoolDlg ::GetSoftwareList()
{

                 HRESULT hres;
                 //Initialize COM.--------------------------------------------
                hres = CoInitializeEx( NULL , COINIT_MULTITHREADED );
                 if (FAILED (hres))
                {

                                 CString str;
                                str.Format( _T ("Failed to initialize COM library.Error Code = %d" ), GetLastError());
                                AfxMessageBox(str);
                }
                                 //DebugLog::Instance().WriteLog("Failed to initialize COM library. Error Code = %d", GetLastError());

                hres = CoInitializeSecurity(
                                 NULL ,
                                -1,                          // COM authentication
                                 NULL ,                        // Authentication services
                                 NULL ,                        // Reserved
                                 RPC_C_AUTHN_LEVEL_DEFAULT ,   // Default authentication
                                 RPC_C_IMP_LEVEL_IMPERSONATE , // Default Impersonation
                                 NULL ,                        // Authentication info
                                 EOAC_NONE ,                   // Additional capabilities
                                 NULL                          // Reserved
                );

                 if (FAILED (hres))
                {
                                 CString str;
                                str.Format( _T ("Failed to initialize security. Error Code = %d" ), GetLastError());
                                AfxMessageBox(str);
                                CoUninitialize();
                                 return ;                    // Program has failed.
                }

                 IWbemLocator *pLoc = NULL ;
                hres = CoCreateInstance(
                                CLSID_WbemLocator,
                                0,
                                 CLSCTX_INPROC_SERVER ,
                                IID_IWbemLocator, ( LPVOID *)&pLoc);

                 if (FAILED (hres))
                {
                 //             DebugLog::Instance().WriteLog("Failed to create IWbemLocator object. Error Code = %d", GetLastError());
                                 CString str;
                                str.Format( _T ("Failed to create IWbemLocator object. Error Code = %d" ), GetLastError());
                                AfxMessageBox(str);

                                CoUninitialize();
                                 return ;                 // Program has failed.
                }

                 IWbemServices *pSvc = NULL ;
                hres = pLoc->ConnectServer(
                                 _bstr_t (L"ROOT\\CIMV2" ), // Object path of WMI namespace
                                 NULL ,                    // User name. NULL = current user
                                 NULL ,                    // User password. NULL = current
                                0,                       // Locale. NULL indicates current
                                 NULL ,                    // Security flags.
                                0,                       // Authority (for example, Kerberos)
                                0,                       // Context object
                                &pSvc                    // pointer to IWbemServices proxy
                );

                 if (FAILED (hres))
                {
                                 CString str;
                                str.Format( _T ("Could not connect. Error Code = %d" ), GetLastError());
                                AfxMessageBox(str);
                                 //DebugLog::Instance().WriteLog("Could not connect. Error Code = %d", GetLastError());
                                pLoc->Release();
                                CoUninitialize();
                                 return ;                // Program has failed.
                }

                 CString str;
                str.Format( _T ("Connected to ROOT\\CIMV2 WMI namespace" ));
                 //AfxMessageBox(str);
                 //DebugLog::Instance().WriteLog("Connected to ROOT\\CIMV2 WMI namespace");

                hres = CoSetProxyBlanket(
                                pSvc,                        // Indicates the proxy to set
                                 RPC_C_AUTHN_WINNT ,           // RPC_C_AUTHN_xxx
                                 RPC_C_AUTHZ_NONE ,            // RPC_C_AUTHZ_xxx
                                 NULL ,                        // Server principal name
                                 RPC_C_AUTHN_LEVEL_CALL ,      // RPC_C_AUTHN_LEVEL_xxx
                                 RPC_C_IMP_LEVEL_IMPERSONATE , // RPC_C_IMP_LEVEL_xxx
                                 NULL ,                        // client identity
                                 EOAC_NONE                     // proxy capabilities
                );

                 if (FAILED (hres))
                {
                                 CString str;
                                str.Format( _T ("Could not set proxy blanket. Error code = %d" ), GetLastError());
                                AfxMessageBox(str);
                                 //DebugLog::Instance().WriteLog("Could not set proxy blanket. Error code = %d", GetLastError());
                                pSvc->Release();
                                pLoc->Release();
                                CoUninitialize();
                                 return ;               // Program has failed.
                }

                 IEnumWbemClassObject * pEnumerator = NULL ;
                hres = pSvc->ExecQuery(
                                 bstr_t ("WQL" ),
                                 bstr_t ("SELECT * FROM Win32_Product" ), /*Win32_OperatingSystem*/
                                 WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY ,
                                 NULL ,
                                &pEnumerator);

                 if (FAILED (hres))
                {
                                 CString str;
                                str.Format( _T ("Query for install software failed. Error code = %d" ), GetLastError());
                                AfxMessageBox(str);
                                pSvc->Release();
                                pLoc->Release();
                                CoUninitialize();
                                 return ;
                }

                 IWbemClassObject *pclsObj = NULL ;
                 ULONG uReturn = 0;
                 while (pEnumerator)
                {
                                 //CString str;
                                 //str.Format(_T("********************************"""));
                 //             AfxMessageBox(str);

                                                 HRESULT hr = pEnumerator->Next(/*WBEM_INFINITE*//*WBEM_NO_WAIT*/ WBEM_INFINITE , 1, &pclsObj, &uReturn);

                                                 if (0 == uReturn)
                                                {
                                                                 int ma = GetLastError();
                                                                 CString str;
                                                                str.Format( _T ("GetLastError() == %d" ), GetLastError());
                                                 //             AfxMessageBox(str);
                                                                 break ;
                                                }
                                                 else
                                                {
                                                                 VARIANT vtProp;
                                                                 // Get the value of the Name property
                                                                hr = pclsObj->Get(L"Name" , 0, &vtProp, NULL, NULL);
                                                                 char * lpszName = _com_util::ConvertBSTRToString(vtProp.bstrVal);

                                                                hr = pclsObj->Get(L"InstallLocation" , 0, &vtProp, NULL, NULL);
                                                                 char * lpszInstallLocation = _com_util::ConvertBSTRToString(vtProp.bstrVal);

                                                                 USES_CONVERSION ;
                                                                m_list.InsertItem(0, A2W (lpszName));
                                                                m_list.SetItemText(0, 1, A2W (lpszInstallLocation));

                                                                VariantClear(&vtProp);

                                                                pclsObj->Release();
                                                }

                }

                 // Cleanup
                 // ========
                pSvc->Release();
                pLoc->Release();
                pEnumerator->Release();
                CoUninitialize();
}

WMI Win32_Product的成员 https://msdn.microsoft.com/en-us/library/aa394378.aspx

[Provider("MSIProv"), Dynamic]
class Win32_Product : CIM_Product
{
  uint16   AssignmentType;
  string   Caption;
  string   Description;
  string   IdentifyingNumber;
  string   InstallDate;
  datetime InstallDate2;
  string   InstallLocation;
  sint16   InstallState;
  string   HelpLink;
  string   HelpTelephone;
  string   InstallSource;
  string   Language;
  string   LocalPackage;
  string   Name;
  string   PackageCache;
  string   PackageCode;
  string   PackageName;
  string   ProductID;
  string   RegOwner;
  string   RegCompany;
  string   SKUNumber;
  string   Transforms;
  string   URLInfoAbout;
  string   URLUpdateInfo;
  string   Vendor;
  uint32   WordCount;
  string   Version;
};

ANSI和UNICODE互转,微软提供,无BUG

https://support.microsoft.com/en-us/kb/138813

/*
* AnsiToUnicode converts the ANSI string pszA to a Unicode string
* and returns the Unicode string through ppszW. Space for the
* the converted string is allocated by AnsiToUnicode.
*/

HRESULT __fastcall AnsiToUnicode( LPCSTR pszA , LPOLESTR * ppszW)
{

                 ULONG cCharacters;
                 DWORD dwError;

                 // If input is null then just return the same.
                 if (NULL == pszA)
                {
                                * ppszW = NULL ;
                                 return NOERROR ;
                }

                 // Determine number of wide characters to be allocated for the
                 // Unicode string.
                cCharacters = strlen( pszA ) + 1;

                 // Use of the OLE allocator is required if the resultant Unicode
                 // string will be passed to another COM component and if that
                 // component will free it. Otherwise you can use your own allocator.
                * ppszW = (LPOLESTR )CoTaskMemAlloc(cCharacters * 2);
                 if (NULL == * ppszW)
                                 return E_OUTOFMEMORY ;

                 // Covert to Unicode.
                 if (0 == MultiByteToWideChar(CP_ACP , 0, pszA, cCharacters,
                                * ppszW , cCharacters))
                {
                                dwError = GetLastError();
                                CoTaskMemFree(* ppszW );
                                * ppszW = NULL ;
                                 return HRESULT_FROM_WIN32(dwError);
                }

                 return NOERROR ;
                 /*
                * UnicodeToAnsi converts the Unicode string pszW to an ANSI string
                * and returns the ANSI string through ppszA. Space for the
                * the converted string is allocated by UnicodeToAnsi.
                */
}

HRESULT __fastcall UnicodeToAnsi( LPCOLESTR pszW , LPSTR * ppszA)
{

                 ULONG cbAnsi, cCharacters;
                 DWORD dwError;

                 // If input is null then just return the same.
                 if (pszW == NULL)
                {
                                * ppszA = NULL ;
                                 return NOERROR ;
                }

                cCharacters = wcslen( pszW ) + 1;
                 // Determine number of bytes to be allocated for ANSI string. An
                 // ANSI string can have at most 2 bytes per character (for Double
                 // Byte Character Strings.)
                cbAnsi = cCharacters * 2;

                 // Use of the OLE allocator is not required because the resultant
                 // ANSI  string will never be passed to another COM component. You
                 // can use your own allocator.
                * ppszA = (LPSTR )CoTaskMemAlloc(cbAnsi);
                 if (NULL == * ppszA)
                                 return E_OUTOFMEMORY ;

                 // Convert to ANSI.
                 if (0 == WideCharToMultiByte(CP_ACP , 0, pszW, cCharacters, * ppszA ,
                                cbAnsi, NULL , NULL ))
                {
                                dwError = GetLastError();
                                CoTaskMemFree(* ppszA );
                                * ppszA = NULL ;
                                 return HRESULT_FROM_WIN32(dwError);
                }
                 return NOERROR ;

}

用法

LPOLESTR pszFileNameW;
AnsiToUnicode(lpszName, &pszFileNameW);
m_list.InsertItem(0, pszFileNameW);

方法2:

char * lpszName = "ABC";
USES_CONVERSION ;
TCHAR *p = A2W (lpszName);

//同样,还有 W2A

方法3

#include <cstdlib>

char * lpszName = "ABC";
TCHAR wszName[32];
mbstowcs(wszName, lpszName, 32);

//UINCODE转ANSI
wcstombs(lpszName, wszName, 32);

VC结束进程

BOOL GetDebugPriv()
{
    HANDLE hToken;
    LUID sedebugnameValue;
    TOKEN_PRIVILEGES tkp;

    if (!OpenProcessToken(GetCurrentProcess(),
    TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , &hToken))
    {
        return FALSE ;
    }

    if (! LookupPrivilegeValue( NULL , SE_DEBUG_NAME , &sedebugnameValue))
    {
        CloseHandle(hToken);
        return FALSE ;
    }

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = sedebugnameValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ;

    if (!AdjustTokenPrivileges(hToken, FALSE , &tkp, sizeof tkp, NULL, NULL))
    {
        CloseHandle(hToken);
        return FALSE ;
    }

    return TRUE ;
}


void CToolDlg ::KillProcess()
{
                GetDebugPriv();

                 PROCESSENTRY32 pe32;
                pe32.dwSize = sizeof (pe32);
                 HANDLE hProcessSnap = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0);
                 if (hProcessSnap == INVALID_HANDLE_VALUE )
                {
                                 MessageBox (L"CreateToolhelp32Snapshot调用失败!\n" );
                                 return ;
                }

                 CString strPrcNameID;
                 BOOL bMore = ::Process32First (hProcessSnap, &pe32);
                 while (bMore)
                {
                                 if (lstrcmp (pe32.szExeFile, _TEXT( "contrlvip.exe")) == 0)
                                {
                                                 HANDLE hTargetProcess = OpenProcess(PROCESS_QUERY_INFORMATION |   // Required by Alpha
                                                                 PROCESS_CREATE_THREAD |   // For CreateRemoteThread
                                                                 PROCESS_VM_OPERATION |   // For VirtualAllocEx/VirtualFreeEx
                                                                 PROCESS_VM_WRITE |  // For WriteProcessMemory
                                                                 PROCESS_TERMINATE ,           //Required to terminate a process using TerminateProcess function
                                                                 FALSE , pe32.th32ProcessID);

                                                 if (hTargetProcess == NULL )
                                                {
                                                                 DWORD ulErrCode = GetLastError();
                                                                 CString strError;
                                                                strError.Format( L"OpenProcess failed,error code:%ld" , ulErrCode);
                                                                AfxMessageBox(strError);
                                                }

                                                 BOOL result = TerminateProcess(hTargetProcess, 0);
                                                 if (!result)
                                                {
                                                                 DWORD ulErrCode = GetLastError();
                                                                 CString strError;
                                                                strError.Format( L"TerminateProcess failed,error code:%ld" , ulErrCode);
                                                                AfxMessageBox(strError);
                                                }
                                }

                                bMore = :: Process32Next (hProcessSnap, &pe32);
                }
                ::CloseHandle(hProcessSnap);
}

VC获取程序所在的目录

CString  GetCurDir()
{
                 char   sDrive[_MAX_DRIVE ];
                 char   sDir[_MAX_DIR ];
                 char   sFilename[_MAX_FNAME ], Filename[_MAX_FNAME];
                 char   sExt[_MAX_EXT ];
                 GetModuleFileName(AfxGetInstanceHandle(), Filename, _MAX_PATH);
                 _tsplitpath(Filename, sDrive, sDir, sFilename, sExt);
                 CString   homeDir(CString (sDrive) + CString(sDir));
                 int   nLen = homeDir.GetLength();

                 if (homeDir.GetAt(nLen - 1)!= '\\' )
                {
                                homeDir += '\\' ;
                }

                 return homeDir;
}