VC 获取软件安装列表

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

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结束进程

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);
}

编译Libgdiplus遇到的问题

https://github.com/mono/libgdiplus/releases 下载最新版本
解压并执行 ./autogen.sh,在执行此步时遇到如下问题,并帖出解决办法

问题:执行 ./autogen.sh时报错 Error: You must have `autoconf’ installed to compile Mono.
解决办法:apt-get install autoconf

问题:执行./autogen.sh报错 Error: You must have `libtool’ installed to compile Mono.
解决:apt-get install libtool

问题:configure: error: You need to install pkg-config
解决: apt-get install pkg-config

问题:No package ‘glib-2.0’ found
解决:apt-get install glib-2.0

问题:No package ‘cairo’ found
解决:apt-get install libcairo2-dev

都解决后,最后执行 make && make install

Supervisor 安装 配置 及 使用

supervisor是微软官方推荐的一个工具,传送门, 所以我们也使用这个工具来管理我们的asp.net core应用进程

服务器环境:ubuntu14.04 x64
安装 apt-get install supervisor
配置文件目录: /etc/supervisor/conf.d
添加配置文件 vi /etc/supervisor/conf.d/xxx.conf

配置内容如下:

[program:sellplatform]
command=/var/www/yiinet.cc/SellPlatform
directory=/var/www/yiinet.cc
autostart=true
autorestart=true
stderr_logfile=/var/log/sellplatform.err.log
stdout_logfile=/var/log/sellplatform.out.log
environment=Hosting__Environment=Development
user=root
stopsignal=INT
redirect_stderr=true

supervisor 相关命令
重启supervisor服务 service supervisor restart
查看状态 supervisorctl status
关闭目标程序 supervisorctl stop sellplatform
启动目标程序 supervisorctl start sellplatform
关闭所有程序 supervisorctl shutdown

相关链接
在Linux上用supervisor运行ASP.NET Core站点的一个坑

SQL SERVER按字母数字的组合排序

SQL SERVER按字母数字的组合排序

SELECT Price, Contact,Number,  GameType, ServerName, Account,Password, Rank, RentDate,  Legends, Detail, IsRent, Id
FROM dbo.AccountInfo
ORDER BY UPPER(LEFT(Number, patindex('%[^a-z]%',Number)-1)) ASC, Convert(int, RIGHT(Number,LEN(Number)- patindex('%[^a-z]%',Number)+1)) ASC, Number ASC

Mysql版本

SELECT  Number
FROM    accountinfo
ORDER   BY         
        CASE WHEN Number REGEXP '^[A-Z]{2}'
            THEN 1
            ELSE 0
        END ASC,
        CASE WHEN Number REGEXP '^[A-Z]{2}'
            THEN LEFT(Number, 2)
            ELSE LEFT(Number, 1)
        END ASC,
        CASE WHEN Number REGEXP '^[A-Z]{2}'
            THEN CAST(RIGHT(Number, LENGTH(Number) - 2) AS SIGNED)
            ELSE CAST(RIGHT(Number, LENGTH(Number) - 1) AS SIGNED)
        END ASC

postgresql版本

SELECT *, (regexp_matches(Number, '[A-Z]+' ))[1], (regexp_matches(Number, '[0-9]+' ))[1] from aaa
    ORDER BY (regexp_matches(Number, '[A-Z]+' ))[1] ASC ,
                  to_number((regexp_matches(Number, '[0-9]+' ))[1], '999999') ASC