Commit bef40403 authored by captainwong's avatar captainwong

wmi

parent 1cbe12a2
......@@ -9,13 +9,13 @@
#include <comdef.h>
#include <comutil.h>
#include <atlconv.h>
#include <jlib/3rdparty/win32/WinReg.hpp>
#include <jlib/utf8.h>
#pragma comment (lib, "comsuppw.lib")
#pragma comment (lib, "wbemuuid.lib")
namespace jlib {
namespace win32 {
namespace DeviceUniqueIdentifier {
namespace detail {
......@@ -70,7 +70,7 @@ inline WQL_QUERY getWQLQuery(QueryType queryType) {
}
static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t *SerialNumber, UINT uSize)
static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t* SerialNumber, UINT uSize)
{
UINT iLen;
UINT i;
......@@ -129,7 +129,7 @@ static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t *SerialNumber, UINT uSize)
// 通过“PNPDeviceID”获取网卡原生MAC地址
static BOOL WMI_DoWithPNPDeviceID(const wchar_t *PNPDeviceID, wchar_t *MacAddress, UINT uSize)
static BOOL WMI_DoWithPNPDeviceID(const wchar_t* PNPDeviceID, wchar_t* MacAddress, UINT uSize)
{
wchar_t DevicePath[MAX_PATH];
HANDLE hDeviceFile;
......@@ -176,7 +176,7 @@ static BOOL WMI_DoWithPNPDeviceID(const wchar_t *PNPDeviceID, wchar_t *MacAddres
}
static BOOL WMI_DoWithProperty(QueryType queryType, wchar_t *szProperty, UINT uSize)
static BOOL WMI_DoWithProperty(QueryType queryType, wchar_t* szProperty, UINT uSize)
{
BOOL isOK = TRUE;
switch (queryType) {
......@@ -320,7 +320,7 @@ bool query(const std::vector<QueryType>& queryTypes, std::vector<std::wstring>&
}
// 获得WMI连接COM接口
IWbemLocator *pLoc = NULL;
IWbemLocator* pLoc = NULL;
hres = CoCreateInstance(
CLSID_WbemLocator,
NULL,
......@@ -334,7 +334,7 @@ bool query(const std::vector<QueryType>& queryTypes, std::vector<std::wstring>&
}
// 通过连接接口连接WMI的内核对象名"ROOT//CIMV2"
IWbemServices *pSvc = NULL;
IWbemServices* pSvc = NULL;
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
NULL,
......@@ -375,7 +375,7 @@ bool query(const std::vector<QueryType>& queryTypes, std::vector<std::wstring>&
auto query = detail::getWQLQuery(queryType);
// 通过请求代理来向WMI发送请求
IEnumWbemClassObject *pEnumerator = NULL;
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t(query.szSelect),
......@@ -392,7 +392,7 @@ bool query(const std::vector<QueryType>& queryTypes, std::vector<std::wstring>&
// 循环枚举所有的结果对象
while (pEnumerator) {
IWbemClassObject *pclsObj = NULL;
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
pEnumerator->Next(
......@@ -436,7 +436,7 @@ bool query(const std::vector<QueryType>& queryTypes, std::vector<std::wstring>&
return ok;
}
std::wstring join_result(const std::vector<std::wstring>& results, const std::wstring & conjunction)
std::wstring join_result(const std::vector<std::wstring>& results, const std::wstring& conjunction)
{
std::wstring result;
auto itBegin = results.cbegin();
......@@ -453,3 +453,4 @@ std::wstring join_result(const std::vector<std::wstring>& results, const std::ws
}
}
}
......@@ -3,8 +3,12 @@
#include <string>
#include <vector>
namespace jlib {
namespace DeviceUniqueIdentifier {
namespace jlib
{
namespace win32
{
namespace DeviceUniqueIdentifier
{
/*
......@@ -138,3 +142,4 @@ std::wstring join_result(const std::vector<std::wstring>& results, const std::ws
}
}
}
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include <Windows.h>
#include <winioctl.h>
#include <WbemIdl.h>
#include <ntddndis.h>
#include <comdef.h>
#include <comutil.h>
#include <atlconv.h>
#include <math.h>
#include <strsafe.h>
#include <tchar.h>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include "../utf8.h"
#pragma comment (lib, "comsuppw.lib")
#pragma comment (lib, "wbemuuid.lib")
namespace jlib {
namespace win32 {
namespace DeviceUniqueIdentifier {
/*
参考1:
《设备唯一标识方法(Unique Identifier):如何在Windows系统上获取设备的唯一标识》
......@@ -100,6 +112,22 @@ enum QueryType : size_t {
WINDOWS_MACHINE_GUID = 1 << 8,
};
static const wchar_t* queryTypeString(QueryType type)
{
switch (type) {
case QueryType::MAC_ADDR: return L"MAC_ADDR ";
case QueryType::MAC_ADDR_REAL: return L"MAC_ADDR_REAL ";
case QueryType::HARDDISK_SERIAL: return L"HARDDISK_SERIAL ";
case QueryType::MOTHERBOARD_UUID: return L"MOTHERBOARD_UUID ";
case QueryType::MOTHERBOARD_MODEL: return L"MOTHERBOARD_MODEL ";
case QueryType::CPU_ID: return L"CPU_ID ";
case QueryType::BIOS_SERIAL: return L"BIOS_SERIAL ";
case QueryType::WINDOWS_PRODUCT_ID: return L"WINDOWS_PRODUCT_ID ";
case QueryType::WINDOWS_MACHINE_GUID: return L"WINDOWS_MACHINE_GUID";
default: return L"UNKNOWN QueryType ";
}
}
enum {
RecommendedQueryTypes = WINDOWS_MACHINE_GUID
| WINDOWS_PRODUCT_ID
......@@ -116,13 +144,15 @@ enum {
,
};
typedef std::unordered_map<QueryType, std::wstring> QueryResults;
/**
* @brief 查询信息
* @param[in] queryTypes QueryType集合
* @param[in,out] results 查询结果集合
* @return 成功或失败
*/
static bool query(size_t queryTypes, std::unordered_map<QueryType, std::wstring>& results);
static bool query(size_t queryTypes, QueryResults& results);
/**
* @brief 查询信息
......@@ -130,7 +160,7 @@ static bool query(size_t queryTypes, std::unordered_map<QueryType, std::wstring>
* @param[in,out] results 查询结果集合
* @return 成功或失败
*/
static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<QueryType, std::wstring>& results);
static bool query(const std::vector<QueryType>& queryTypes, QueryResults& results);
/**
* @brief 连接查询结果为一个字符串
......@@ -138,30 +168,13 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
* @param[in,out] conjunction 连词
* @return 将结果以连词连接起来组成的字符串
*/
static std::wstring join_result(const std::vector<std::wstring>& results, const std::wstring& conjunction);
static std::wstring join_result(const QueryResults& results, const std::wstring& conjunction);
}
}
// Implementation
#include <Windows.h>
#include <algorithm>
#include <math.h>
#include <strsafe.h>
#include <tchar.h>
#include <ntddndis.h>
#include <WbemIdl.h>
#include <comdef.h>
#include <comutil.h>
#include <atlconv.h>
#include <jlib/utf8.h>
#pragma comment (lib, "comsuppw.lib")
#pragma comment (lib, "wbemuuid.lib")
namespace jlib {
namespace DeviceUniqueIdentifier {
namespace detail {
namespace detail
{
struct DeviceProperty {
enum { PROPERTY_MAX_LEN = 128 }; // 属性字段最大长度
......@@ -213,8 +226,7 @@ inline WQL_QUERY getWQLQuery(QueryType queryType) {
}
}
static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t *SerialNumber, UINT uSize)
static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t* SerialNumber, UINT uSize)
{
UINT iLen;
UINT i;
......@@ -271,9 +283,8 @@ static BOOL WMI_DoWithHarddiskSerialNumber(wchar_t *SerialNumber, UINT uSize)
return TRUE;
}
// 通过“PNPDeviceID”获取网卡原生MAC地址
static BOOL WMI_DoWithPNPDeviceID(const wchar_t *PNPDeviceID, wchar_t *MacAddress, UINT uSize)
static BOOL WMI_DoWithPNPDeviceID(const wchar_t* PNPDeviceID, wchar_t* MacAddress, UINT uSize)
{
wchar_t DevicePath[MAX_PATH];
HANDLE hDeviceFile;
......@@ -319,8 +330,7 @@ static BOOL WMI_DoWithPNPDeviceID(const wchar_t *PNPDeviceID, wchar_t *MacAddres
return isOK;
}
static BOOL WMI_DoWithProperty(QueryType queryType, wchar_t *szProperty, UINT uSize)
static BOOL WMI_DoWithProperty(QueryType queryType, wchar_t* szProperty, UINT uSize)
{
BOOL isOK = TRUE;
switch (queryType) {
......@@ -341,8 +351,6 @@ static BOOL WMI_DoWithProperty(QueryType queryType, wchar_t *szProperty, UINT uS
return isOK;
}
static std::wstring getMachineGUID()
{
std::wstring res;
......@@ -397,10 +405,10 @@ static std::wstring getMachineGUID()
return res;
}
} // end of namespace detail
} // namespace detail
static bool query(size_t queryTypes, std::unordered_map<QueryType, std::wstring>& results)
static bool query(size_t queryTypes, QueryResults& results)
{
std::vector<QueryType> vec;
......@@ -438,30 +446,30 @@ static bool query(size_t queryTypes, std::unordered_map<QueryType, std::wstring>
}
// 基于Windows Management Instrumentation(Windows管理规范)
static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<QueryType, std::wstring>& results)
static bool query(const std::vector<QueryType>& queryTypes, QueryResults& results)
{
bool ok = false;
// 初始化COM COINIT_APARTMENTTHREADED
HRESULT hres = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
_com_error ce(hres);
qDebug() << "CoInitializeEx with COINIT_MULTITHREADED failed:\n" << ce.Error() << QString::fromWCharArray(ce.ErrorMessage()); //
#endif
if (hres == 0x80010106) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "already initilized, pass"; //
#endif
} else {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "trying CoInitializeEx with COINIT_APARTMENTTHREADED"; //
#endif
hres = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "CoInitializeEx with COINIT_APARTMENTTHREADED failed, exit";
#endif
return false;
......@@ -482,16 +490,16 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
NULL
);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "CoInitializeSecurity:" << hres << QString::fromWCharArray(_com_error(hres).ErrorMessage());
#else
#elif defined(__AFXWIN_H__)
CString msg;
msg.Format(L"0x%X : %s", hres, _com_error(hres).ErrorMessage());
MessageBoxW(NULL, msg, L"error", MB_ICONERROR);
#endif
if (hres == E_OUTOFMEMORY) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "E_OUTOFMEMORY";
#else
MessageBoxW(NULL, L"E_OUTOFMEMORY", L"error", MB_ICONERROR);
......@@ -502,7 +510,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
}
}
// 获得WMI连接COM接口
IWbemLocator *pLoc = NULL;
IWbemLocator* pLoc = NULL;
hres = CoCreateInstance(
CLSID_WbemLocator,
NULL,
......@@ -511,7 +519,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
reinterpret_cast<LPVOID*>(&pLoc)
);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "CoCreateInstance:" << QString::fromWCharArray(_com_error(hres).ErrorMessage());
#endif
CoUninitialize();
......@@ -519,7 +527,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
}
// 通过连接接口连接WMI的内核对象名"ROOT//CIMV2"
IWbemServices *pSvc = NULL;
IWbemServices* pSvc = NULL;
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
NULL,
......@@ -531,7 +539,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
&pSvc
);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "ConnectServer:" << QString::fromWCharArray(_com_error(hres).ErrorMessage());
#endif
pLoc->Release();
......@@ -551,7 +559,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
EOAC_NONE
);
if (FAILED(hres)) {
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "CoSetProxyBlanket:" << QString::fromWCharArray(_com_error(hres).ErrorMessage());
#endif
pSvc->Release();
......@@ -569,7 +577,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
auto query = detail::getWQLQuery(queryType);
// 通过请求代理来向WMI发送请求
IEnumWbemClassObject *pEnumerator = NULL;
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t(query.szSelect),
......@@ -581,7 +589,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
//pSvc->Release();
//pLoc->Release();
//CoUninitialize();
#ifndef __AFXWIN_H__
#ifdef QT_VERSION
qDebug() << "ExecQuery:\n" << QString::fromWCharArray(query.szSelect) << '\n' << QString::fromWCharArray(_com_error(hres).ErrorMessage());
#endif
results[queryType] = _com_error(hres).ErrorMessage();
......@@ -590,7 +598,7 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
// 循环枚举所有的结果对象
while (pEnumerator) {
IWbemClassObject *pclsObj = NULL;
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
pEnumerator->Next(
......@@ -634,20 +642,22 @@ static bool query(const std::vector<QueryType>& queryTypes, std::unordered_map<Q
return ok;
}
static std::wstring join_result(const std::vector<std::wstring>& results, const std::wstring & conjunction)
static std::wstring join_result(const QueryResults& results, const std::wstring& conjunction)
{
std::wstring result;
auto itBegin = results.cbegin();
auto itEnd = results.cend();
if (itBegin != itEnd) {
result = *itBegin++;
result = itBegin->second;
itBegin++;
}
for (; itBegin != itEnd; itBegin++) {
result += conjunction;
result += *itBegin;
result += itBegin->second;
}
return result;
}
}
}
} // namespace DeviceUniqueIdentifier
} // namespace win32
} // namespace jlib
#pragma once
#include "../utf8.h"
namespace jlib
{
inline const wchar_t* FormatWSAError(int errornumber)
{
switch (errornumber) {
case WSANOTINITIALISED:
return L"A successful WSAStartup call must occur before using this function. ";
break;
case WSAENETDOWN:
return L"The network subsystem has failed. ";
break;
case WSAEACCES:
return L"The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address. ";
break;
case WSAEINVAL:
return L"An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled. ";
break;
case WSAEINTR:
return L"A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. ";
break;
case WSAEINPROGRESS:
return L"A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. ";
break;
case WSAEFAULT:
return L"The buf or to parameters are not part of the user address space, or the tolen parameter is too small. ";
break;
case WSAENETRESET:
return L"The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. ";
break;
case WSAENOBUFS:
return L"No buffer space is available. ";
break;
case WSAENOTCONN:
return L"The socket is not connected (connection-oriented sockets only. ";
break;
case WSAENOTSOCK:
return L"The descriptor is not a socket. ";
break;
case WSAEOPNOTSUPP:
return L"MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations. ";
break;
case WSAESHUTDOWN:
return L"The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. ";
break;
case WSAEWOULDBLOCK:
return L"The socket is marked as nonblocking and the requested operation would block. ";
break;
case WSAEMSGSIZE:
return L"The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. ";
break;
case WSAEHOSTUNREACH:
return L"The remote host cannot be reached from this host at this time. ";
break;
case WSAECONNABORTED:
return L"The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. ";
break;
case WSAECONNRESET:
return L"The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a \"Port Unreachable\" ICMP packet. The application should close the socket as it is no longer usable. ";
break;
case WSAEADDRNOTAVAIL:
return L"The remote address is not a valid address, for example, ADDR_ANY. ";
break;
case WSAEAFNOSUPPORT:
return L"Addresses in the specified family cannot be used with this socket. ";
break;
case WSAEDESTADDRREQ:
return L"A destination address is required. ";
break;
case WSAENETUNREACH:
return L"The network cannot be reached from this host at this time. ";
break;
case WSAETIMEDOUT:
return L"The connection has been dropped, because of a network failure or because the system on the other end went down without notice. ";
break;
default:{
static wchar_t buf[1024] = { 0 };
swprintf_s(buf, L"Unknown socket error %d.", errornumber);
return buf;
}break;
}
}
namespace win32
{
inline const char* FormatWSAErrorA(int errornumber)
inline const wchar_t* FormatWSAError(int errornumber)
{
switch (errornumber) {
case WSANOTINITIALISED:
return L"A successful WSAStartup call must occur before using this function. ";
case WSAENETDOWN:
return L"The network subsystem has failed. ";
case WSAEACCES:
return L"The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address. ";
case WSAEINVAL:
return L"An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled. ";
case WSAEINTR:
return L"A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. ";
case WSAEINPROGRESS:
return L"A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. ";
case WSAEFAULT:
return L"The buf or to parameters are not part of the user address space, or the tolen parameter is too small. ";
case WSAENETRESET:
return L"The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. ";
case WSAENOBUFS:
return L"No buffer space is available. ";
case WSAENOTCONN:
return L"The socket is not connected (connection-oriented sockets only. ";
case WSAENOTSOCK:
return L"The descriptor is not a socket. ";
case WSAEOPNOTSUPP:
return L"MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations. ";
case WSAESHUTDOWN:
return L"The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. ";
case WSAEWOULDBLOCK:
return L"The socket is marked as nonblocking and the requested operation would block. ";
case WSAEMSGSIZE:
return L"The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. ";
case WSAEHOSTUNREACH:
return L"The remote host cannot be reached from this host at this time. ";
case WSAECONNABORTED:
return L"The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. ";
case WSAECONNRESET:
return L"The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a \"Port Unreachable\" ICMP packet. The application should close the socket as it is no longer usable. ";
case WSAEADDRNOTAVAIL:
return L"The remote address is not a valid address, for example, ADDR_ANY. ";
case WSAEAFNOSUPPORT:
return L"Addresses in the specified family cannot be used with this socket. ";
case WSAEDESTADDRREQ:
return L"A destination address is required. ";
case WSAENETUNREACH:
return L"The network cannot be reached from this host at this time. ";
case WSAETIMEDOUT:
return L"The connection has been dropped, because of a network failure or because the system on the other end went down without notice. ";
default:
{
return utf8::w2a(FormatWSAError(errornumber)).c_str();
static wchar_t buf[1024] = { 0 };
swprintf_s(buf, L"Unknown socket error %d.", errornumber);
return buf;
}
}
}
inline const char* FormatWSAErrorA(int errornumber)
{
return utf8::w2a(FormatWSAError(errornumber)).c_str();
}
};
}
}
......@@ -2,6 +2,11 @@
#include <windows.h>
namespace jlib
{
namespace win32
{
inline bool Utf16ToUtf8(const wchar_t* utf16String, char* utf8Buffer, size_t szBuff)
{
size_t request_size = WideCharToMultiByte(CP_UTF8, 0, utf16String, -1, NULL, 0, 0, 0);
......@@ -25,24 +30,24 @@ inline bool Utf8ToUtf16(const char* utf8String, wchar_t* utf16Buffer, size_t szB
/**************UNICODE-ANSI mutually transform**************************/
// need be manuly delete
__forceinline LPSTR Utf16ToAnsi(const wchar_t * const wSrc)
__forceinline LPSTR Utf16ToAnsi(const wchar_t* const wSrc)
{
char* pElementText;
int iTextLen;
iTextLen = WideCharToMultiByte(CP_ACP, 0, wSrc, -1, NULL, 0, NULL, NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, sizeof(char)* (iTextLen + 1));
memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP, 0, wSrc, -1, pElementText, iTextLen, NULL, NULL);
return pElementText;
}
__forceinline BOOL Utf16ToAnsiUseCharArray(const wchar_t * const wSrc,
char *ansiArr, DWORD ansiArrLen)
__forceinline BOOL Utf16ToAnsiUseCharArray(const wchar_t* const wSrc,
char* ansiArr, DWORD ansiArrLen)
{
int iTextLen = WideCharToMultiByte(CP_ACP, 0, wSrc, -1, NULL, 0, NULL, NULL);
if (static_cast<DWORD>(iTextLen) < ansiArrLen) {
memset((void*)ansiArr, 0, sizeof(char)* (iTextLen + 1));
memset((void*)ansiArr, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP, 0, wSrc, -1, ansiArr, iTextLen, NULL, NULL);
return TRUE;
}
......@@ -51,9 +56,9 @@ __forceinline BOOL Utf16ToAnsiUseCharArray(const wchar_t * const wSrc,
__forceinline wchar_t* AnsiToUtf16(PCSTR ansiSrc)
{
wchar_t *pWide;
wchar_t* pWide;
int iUnicodeLen = ::MultiByteToWideChar(CP_ACP,
0, ansiSrc, -1, NULL, 0);
0, ansiSrc, -1, NULL, 0);
pWide = new wchar_t[iUnicodeLen + 1];
memset(pWide, 0, (iUnicodeLen + 1) * sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP, 0, ansiSrc, -1, (LPWSTR)pWide, iUnicodeLen);
......@@ -63,7 +68,7 @@ __forceinline wchar_t* AnsiToUtf16(PCSTR ansiSrc)
__forceinline BOOL AnsiToUtf16Array(PCSTR ansiSrc, wchar_t* warr, int warr_len)
{
int iUnicodeLen = ::MultiByteToWideChar(CP_ACP,
0, ansiSrc, -1, NULL, 0);
0, ansiSrc, -1, NULL, 0);
if (warr_len >= iUnicodeLen) {
memset(warr, 0, (iUnicodeLen + 1) * sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP, 0, ansiSrc, -1, (LPWSTR)warr, iUnicodeLen);
......@@ -74,7 +79,7 @@ __forceinline BOOL AnsiToUtf16Array(PCSTR ansiSrc, wchar_t* warr, int warr_len)
__forceinline wchar_t* Utf8ToUtf16(PCSTR ansiSrc)
{
wchar_t *pWide;
wchar_t* pWide;
int iUnicodeLen = ::MultiByteToWideChar(CP_UTF8,
0, ansiSrc, -1, NULL, 0);
pWide = new wchar_t[iUnicodeLen + 1];
......@@ -87,9 +92,11 @@ __forceinline wchar_t* Utf8ToUtf16(PCSTR ansiSrc)
__inline const char* Utf16ToUtf8(const wchar_t* utf16, int& out_len)
{
out_len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, 0, 0);
char *p8 = new char[out_len + 1];
memset(p8, 0, (out_len + 1) * sizeof(wchar_t));
char* p8 = new char[out_len + 1];
memset(p8, 0, (out_len + 1) * sizeof(char));
::WideCharToMultiByte(CP_UTF8, 0, utf16, -1, p8, out_len, 0, 0);
return p8;
}
}
}
......@@ -2,9 +2,13 @@
#include <windows.h>
#include <string>
namespace jlib{
namespace jlib
{
namespace win32
{
inline bool to_clipboard(const std::wstring &s)
inline bool to_clipboard(const std::wstring& s)
{
if (!OpenClipboard(nullptr)) return false;
if (!EmptyClipboard()) return false;
......@@ -50,5 +54,5 @@ inline std::wstring from_clipboard()
return text;
}
}
\ No newline at end of file
}
}
......@@ -2,30 +2,31 @@
#include <Windows.h>
#include <string>
namespace jlib {
inline bool get_file_open_dialog_result(std::wstring& path,
namespace jlib
{
namespace win32
{
inline bool get_file_open_dialog_result(std::wstring& path,
HWND hWnd = nullptr,
const std::wstring& default_folder = L"",
const std::wstring& ext = L"",
UINT cFileTypes = 0,
const COMDLG_FILTERSPEC *rgFilterSpec = nullptr) {
const COMDLG_FILTERSPEC * rgFilterSpec = nullptr)
{
bool ok = false;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED |
COINIT_DISABLE_OLE1DDE);
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr)) {
IFileOpenDialog *pFileOpen;
IFileOpenDialog* pFileOpen;
// Create the FileOpenDialog object.
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));
if (SUCCEEDED(hr)) {
if (!default_folder.empty()) {
IShellItem *psiFolder;
IShellItem* psiFolder;
//LPCWSTR szFilePath = SysAllocStringLen(default_folder.data(), default_folder.size());
//hr = SHCreateItemFromParsingName(szFilePath, NULL, IID_PPV_ARGS(&psiFolder));
//if (SUCCEEDED(hr))
......@@ -59,7 +60,7 @@ inline bool get_file_open_dialog_result(std::wstring& path,
// Get the file name from the dialog box.
if (SUCCEEDED(hr)) {
IShellItem *pItem;
IShellItem* pItem;
hr = pFileOpen->GetResult(&pItem);
if (SUCCEEDED(hr)) {
PWSTR pszFilePath;
......@@ -89,24 +90,21 @@ inline bool get_save_as_dialog_path(std::wstring& path,
const std::wstring& default_name = L"",
const std::wstring& ext = L"",
UINT cFileTypes = 0,
const COMDLG_FILTERSPEC *rgFilterSpec = nullptr) {
const COMDLG_FILTERSPEC * rgFilterSpec = nullptr)
{
bool ok = false;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED |
COINIT_DISABLE_OLE1DDE);
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr)) {
IFileSaveDialog *pFileSave;
IFileSaveDialog* pFileSave;
// Create the FileOpenDialog object.
hr = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_ALL,
IID_IFileSaveDialog, reinterpret_cast<void**>(&pFileSave));
if (SUCCEEDED(hr)) {
if (!default_folder.empty()) {
IShellItem *psiFolder;
IShellItem* psiFolder;
//LPCWSTR szFilePath = SysAllocStringLen(default_folder.data(), default_folder.size());
//hr = SHCreateItemFromParsingName(szFilePath, NULL, IID_PPV_ARGS(&psiFolder));
//if (SUCCEEDED(hr))
......@@ -130,7 +128,7 @@ inline bool get_save_as_dialog_path(std::wstring& path,
if (!ext.empty()) {
pFileSave->SetDefaultExtension(ext.data());
}
if (cFileTypes != 0 && rgFilterSpec) {
pFileSave->SetFileTypes(cFileTypes, rgFilterSpec);
}
......@@ -144,7 +142,7 @@ inline bool get_save_as_dialog_path(std::wstring& path,
// Get the file name from the dialog box.
if (SUCCEEDED(hr)) {
IShellItem *pItem;
IShellItem* pItem;
hr = pFileSave->GetResult(&pItem);
if (SUCCEEDED(hr)) {
PWSTR pszFilePath;
......@@ -169,3 +167,4 @@ inline bool get_save_as_dialog_path(std::wstring& path,
}
}
}
......@@ -7,6 +7,7 @@
#pragma comment(lib, "Shell32.lib")
namespace jlib {
namespace win32 {
inline std::wstring get_exe_path()
{
......@@ -24,22 +25,22 @@ inline std::string get_exe_path_a()
return std::string(path).substr(0, pos);
}
inline std::wstring integrate_path(const std::wstring& path, wchar_t replace_by = L'_'){
static const wchar_t filter[] = L"\\/:*?\"<>| ";
auto ret = path;
for (auto c : filter) {
std::replace(ret.begin(), ret.end(), c, replace_by);
}
return ret;
inline std::wstring integrate_path(const std::wstring& path, wchar_t replace_by = L'_') {
static const wchar_t filter[] = L"\\/:*?\"<>| ";
auto ret = path;
for (auto c : filter) {
std::replace(ret.begin(), ret.end(), c, replace_by);
}
return ret;
}
inline std::string integrate_path(const std::string& path, char replace_by = '_'){
static const char filter[] = "\\/:*?\"<>| ";
auto ret = path;
for (auto c : filter) {
std::replace(ret.begin(), ret.end(), c, replace_by);
}
return ret;
inline std::string integrate_path(const std::string& path, char replace_by = '_') {
static const char filter[] = "\\/:*?\"<>| ";
auto ret = path;
for (auto c : filter) {
std::replace(ret.begin(), ret.end(), c, replace_by);
}
return ret;
}
inline std::wstring get_special_folder(int csidl) {
......@@ -60,6 +61,5 @@ inline std::string get_special_folder_a(int csidl) {
return std::string();
}
}
}
......@@ -71,10 +71,8 @@
namespace jlib
{
namespace win32
{
namespace reg
{
......@@ -927,7 +925,5 @@ inline std::wstring RegKey::regTypeToString(const DWORD regType)
}
} // namespace reg
} // namespace win32
} // namespace jlib
......@@ -8,6 +8,8 @@
namespace jlib
{
namespace win32
{
//! get first ipv4 of domain
static std::string resolve(const std::string& domain)
......@@ -154,3 +156,4 @@ static std::string resolve(const std::string& domain)
}
}
}
#pragma once
#include <Windows.h>
#include <comdef.h>
#include <WbemIdl.h>
#include <atlbase.h>
#include <atlcom.h>
#include <string>
#include <functional>
#pragma comment (lib, "comsuppw.lib")
#pragma comment (lib, "wbemuuid.lib")
#define JLIB_CHECK_HR(hr) if (FAILED(hr)) break;
#define JLIB_CHECK_HR2(hr, errorFunc) if (FAILED(hr)) { if (errorFunc) { errorFunc(hr, _com_error(hr).ErrorMessage()); } break; }
#define JLIB_CHECK_WMI_HR(hr) if ((hr) != WBEM_S_NO_ERROR) break;
#define JLIB_CHECK_WMI_HR2(hr, errorFunc) if ((hr) != WBEM_S_NO_ERROR) { if (errorFunc) { errorFunc(hr, _com_error(hr).ErrorMessage()); }break; }
namespace jlib
{
namespace win32
{
namespace wmi
{
typedef std::function<void(HRESULT, const std::wstring&)> ErrorFunc;
typedef std::function<void(const std::wstring&, const std::wstring&)> OutputFunc;
class WmiBase
{
public:
WmiBase(const std::wstring& _namespace, OutputFunc outputFunc, ErrorFunc errorFunc = nullptr)
: namespace_(_namespace)
, outputFunc_(outputFunc)
, errorFunc_(errorFunc)
{
}
~WmiBase() {
services_.Release();
CoUninitialize();
}
bool prepare() {
do {
HRESULT hr = E_FAIL;
if (!initCom(hr)) {
if (errorFunc_) {
errorFunc_(hr, _com_error(hr).ErrorMessage());
}
break;
}
hr = setComSecurityLevel();
JLIB_CHECK_HR2(hr, errorFunc_);
CComPtr<IWbemLocator> locator = {};
hr = obtainWbemLocator(locator);
JLIB_CHECK_HR2(hr, errorFunc_);
hr = connect(locator, services_);
JLIB_CHECK_HR2(hr, errorFunc_);
hr = setProxySecurityLevel(services_);
JLIB_CHECK_HR2(hr, errorFunc_);
return true;
} while (0);
return false;
}
bool execute(const std::wstring& wql) {
HRESULT hr = WBEM_S_FALSE;
do {
assert(services_);
CComPtr<IEnumWbemClassObject> pEnumerator = NULL;
hr = services_->ExecQuery(
CComBSTR("WQL"),
CComBSTR(wql.c_str()),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
JLIB_CHECK_WMI_HR2(hr, errorFunc_);
ULONG uReturn = 0;
while (pEnumerator) {
CComPtr<IWbemClassObject> object = NULL;
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
if (0 == uReturn) { break; }
parseIWbemClassObject(object);
}
} while (0);
return hr;
}
HRESULT parseIWbemClassObject(CComPtr<IWbemClassObject> object) {
HRESULT hr = WBEM_S_NO_ERROR;
do {
CComVariant vtClass;
hr = object->BeginEnumeration(WBEM_FLAG_LOCAL_ONLY);
do {
CComBSTR key;
CComVariant value;
CIMTYPE type;
LONG flavor = 0;
hr = object->Next(0, &key, &value, &type, &flavor);
if (WBEM_S_NO_MORE_DATA == hr) { break; }
JLIB_CHECK_WMI_HR2(hr, errorFunc_);
hr = parseSingleItem(key, value, type, flavor);
} while (WBEM_S_NO_ERROR == hr);
hr = object->EndEnumeration();
} while (0);
return hr;
}
HRESULT parseSingleItem(CComBSTR key, CComVariant value, CIMTYPE type, LONG flavor) {
HRESULT hr = WBEM_S_NO_ERROR;
switch (value.vt) {
case VT_UNKNOWN:
parseUnknownItem(key, value, type, flavor);
break;
default:
parseItem(key, value, type, flavor);
break;
}
return hr;
}
void parseItem(CComBSTR key, CComVariant value, CIMTYPE type, LONG flavor) {
std::wstring Key = key.m_str;
std::wstring Value;
switch (value.vt) {
case VT_BSTR:
Value = value.bstrVal;
break;
case VT_I1:
case VT_I2:
case VT_I4:
case VT_I8:
case VT_INT:
case VT_UI8:
case VT_UI1:
case VT_UI2:
case VT_UI4:
case VT_UINT:
Value = std::to_wstring(value.intVal);
break;
case VT_BOOL:
Value = value.boolVal ? L"TRUE" : L"FALSE";
break;
case VT_NULL:
Value = L"NULL";
break;
default:
ATLASSERT(FALSE);
break;
}
outputFunc_(Key, Value);
}
HRESULT parseUnknownItem(CComBSTR key, CComVariant value, CIMTYPE type, LONG flavor) {
HRESULT hr = WBEM_S_NO_ERROR;
if (NULL == value.punkVal) {
return hr;
}
// object类型转换成IWbemClassObject接口指针,通过该指针枚举其他属性
CComPtr<IWbemClassObject> pObjInstance = (IWbemClassObject*)value.punkVal;
do {
hr = pObjInstance->BeginEnumeration(WBEM_FLAG_LOCAL_ONLY);
JLIB_CHECK_HR2(hr, errorFunc_);
CComBSTR newKey;
CComVariant newValue;
CIMTYPE newtype;
LONG newFlavor = 0;
hr = pObjInstance->Next(0, &newKey, &newValue, &newtype, &newFlavor);
JLIB_CHECK_HR2(hr, errorFunc_);
parseItem(newKey, newValue, newtype, newFlavor);
} while (WBEM_S_NO_ERROR == hr);
hr = pObjInstance->EndEnumeration();
return WBEM_S_NO_ERROR;
}
protected:
bool initCom(HRESULT& hr) {
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr)) {
if (hr == 0x80010106) {
// already initilized, pass
} else {
hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (FAILED(hr)) {
return false;
}
}
}
return true;
}
HRESULT setComSecurityLevel() {
return CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL
);
}
HRESULT obtainWbemLocator(CComPtr<IWbemLocator>& locator) {
return CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
(LPVOID*)& locator
);
}
HRESULT connect(CComPtr<IWbemLocator> locator, CComPtr<IWbemServices>& services) {
return locator->ConnectServer(CComBSTR(namespace_.data()),
NULL, NULL, NULL, 0, NULL, NULL, &services);
}
HRESULT setProxySecurityLevel(CComPtr<IWbemServices> services) {
return CoSetProxyBlanket(
services, // 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
);
}
protected:
std::wstring namespace_ = {};
CComPtr<IWbemServices> services_ = {};
OutputFunc outputFunc_ = {};
ErrorFunc errorFunc_ = {};
};
} // namespace wmi
} // namespace win32
} // namespace jlib
......@@ -57,17 +57,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "win32", "win32", "{B5D9E71E
..\jlib\win32\DeviceUniqueIdentifier.cpp = ..\jlib\win32\DeviceUniqueIdentifier.cpp
..\jlib\win32\DeviceUniqueIdentifier.h = ..\jlib\win32\DeviceUniqueIdentifier.h
..\jlib\win32\deviceuniqueidentifierheaderonly.h = ..\jlib\win32\deviceuniqueidentifierheaderonly.h
..\jlib\win32\file_op = ..\jlib\win32\file_op
..\jlib\win32\file_op.h = ..\jlib\win32\file_op.h
..\jlib\win32\memory_micros.h = ..\jlib\win32\memory_micros.h
..\jlib\win32\MtVerify.h = ..\jlib\win32\MtVerify.h
..\jlib\win32\MtVerify.h.bak = ..\jlib\win32\MtVerify.h.bak
..\jlib\win32\MyWSAError.h = ..\jlib\win32\MyWSAError.h
..\jlib\win32\odbccp32.lib = ..\jlib\win32\odbccp32.lib
..\jlib\win32\path_op.h = ..\jlib\win32\path_op.h
..\jlib\win32\registry.h = ..\jlib\win32\registry.h
..\jlib\win32\resolve.h = ..\jlib\win32\resolve.h
..\jlib\win32\UnicodeTool.h = ..\jlib\win32\UnicodeTool.h
..\jlib\win32\wmi.h = ..\jlib\win32\wmi.h
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mfc", "mfc", "{9A3F45EB-C57C-4789-8177-0DEFCC5AFD0E}"
......@@ -221,6 +219,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "View", "View", "{16CAD8DD-E
..\jlib\qt\View\RndButton.h = ..\jlib\qt\View\RndButton.h
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_clipboard", "test_clipboard\test_clipboard.vcxproj", "{904EC99B-A012-4134-AE6F-E21635FB602F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_wmi", "test_wmi\test_wmi.vcxproj", "{79A2C0A6-B8BB-406F-A732-C6300A611EC8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
......@@ -323,6 +325,22 @@ Global
{175611D7-9C38-4269-B0B4-66DE9555A8EB}.Release|x64.Build.0 = Release|x64
{175611D7-9C38-4269-B0B4-66DE9555A8EB}.Release|x86.ActiveCfg = Release|Win32
{175611D7-9C38-4269-B0B4-66DE9555A8EB}.Release|x86.Build.0 = Release|Win32
{904EC99B-A012-4134-AE6F-E21635FB602F}.Debug|x64.ActiveCfg = Debug|x64
{904EC99B-A012-4134-AE6F-E21635FB602F}.Debug|x64.Build.0 = Debug|x64
{904EC99B-A012-4134-AE6F-E21635FB602F}.Debug|x86.ActiveCfg = Debug|Win32
{904EC99B-A012-4134-AE6F-E21635FB602F}.Debug|x86.Build.0 = Debug|Win32
{904EC99B-A012-4134-AE6F-E21635FB602F}.Release|x64.ActiveCfg = Release|x64
{904EC99B-A012-4134-AE6F-E21635FB602F}.Release|x64.Build.0 = Release|x64
{904EC99B-A012-4134-AE6F-E21635FB602F}.Release|x86.ActiveCfg = Release|Win32
{904EC99B-A012-4134-AE6F-E21635FB602F}.Release|x86.Build.0 = Release|Win32
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Debug|x64.ActiveCfg = Debug|x64
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Debug|x64.Build.0 = Debug|x64
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Debug|x86.ActiveCfg = Debug|Win32
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Debug|x86.Build.0 = Debug|Win32
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Release|x64.ActiveCfg = Release|x64
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Release|x64.Build.0 = Release|x64
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Release|x86.ActiveCfg = Release|Win32
{79A2C0A6-B8BB-406F-A732-C6300A611EC8}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -360,6 +378,8 @@ Global
{0E82BB61-0D27-42B4-8F11-98DB2A21C168} = {F118E1C9-F461-4CAA-A0F1-75F5A5C8ADF3}
{42039C84-62EE-4F71-A4B9-E9DB2880357C} = {F118E1C9-F461-4CAA-A0F1-75F5A5C8ADF3}
{16CAD8DD-EF99-4A38-B5AA-BF86FC7A07AB} = {F118E1C9-F461-4CAA-A0F1-75F5A5C8ADF3}
{904EC99B-A012-4134-AE6F-E21635FB602F} = {0E6598D3-602D-4552-97F7-DC5AB458D553}
{79A2C0A6-B8BB-406F-A732-C6300A611EC8} = {0E6598D3-602D-4552-97F7-DC5AB458D553}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A8EBEA58-739C-4DED-99C0-239779F57D5D}
......
#include <jlib/win32/DeviceUniqueIdentifierHeaderOnly.h>
#include <stdio.h>
#include <algorithm>
#include <locale.h>
int main()
{
std::locale::global(std::locale(""));
using namespace jlib::DeviceUniqueIdentifier;
std::vector<std::wstring> results;
/*query(RecommendedQueryTypes, results);
auto str = join_result(results, L"\n");
std::wcout << str << std::endl;*/
results.clear();
query(AllQueryTypes, results);
std::wstring str;
std::vector<std::wstring> types = {
L"MAC_ADDR 网卡MAC地址",
L"MAC_ADDR_REAL 网卡原生MAC地址",
L"HARDDISK_SERIAL 主硬盘序列号",
L"MOTHERBOARD_UUID 主板序列号",
L"MOTHERBOARD_MODEL 主板型号",
L"CPU_ID 处理器序列号",
L"BIOS_SERIAL BIOS序列号",
L"WINDOWS_PRODUCT_ID Windows产品ID",
L"WINDOWS_MACHINE_GUID Windows机器码",
};
for (size_t i = 0; i < min(types.size(), results.size()); i++) {
printf("%ls:\n%ls\n\n", types[i].c_str(), results[i].c_str());
}
//auto str = join_result(results, L"\n");
//std::wcout << std::endl << str << std::endl;
system("pause");
}
\ No newline at end of file
#include <jlib/win32/DeviceUniqueIdentifierHeaderOnly.h>
#include <stdio.h>
#include <algorithm>
#include <locale.h>
int main()
{
std::locale::global(std::locale(""));
using namespace jlib::win32::DeviceUniqueIdentifier;
QueryResults results;
printf("Query RecommendedQueryTypes:\n");
query(RecommendedQueryTypes, results);
for (auto iter = results.begin(); iter != results.end(); iter++) {
printf("%ls: %ls\n", queryTypeString(iter->first), iter->second.data());
}
printf("\nQuery AllQueryTypes:\n");
results.clear();
query(AllQueryTypes, results);
for (auto iter = results.begin(); iter != results.end(); iter++) {
printf("%ls: %ls\n", queryTypeString(iter->first), iter->second.data());
}
printf("\nJoined results:\n%ls\n", join_result(results, L",").data());
system("pause");
}
\ No newline at end of file
......@@ -29,14 +29,14 @@
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
......@@ -120,7 +120,7 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="test.cpp" />
<ClCompile Include="testDeviceUniqueIdentifierHeaderOnly.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
......
......@@ -15,7 +15,7 @@
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="test.cpp">
<ClCompile Include="testDeviceUniqueIdentifierHeaderOnly.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
......
#include "../../jlib/win32/clipboard.h"
#include <assert.h>
using namespace jlib::win32;
int main()
{
std::wstring txt = L"Hello World!";
to_clipboard(txt);
auto txt2 = from_clipboard();
assert(txt == txt2);
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{904EC99B-A012-4134-AE6F-E21635FB602F}</ProjectGuid>
<RootNamespace>testclipboard</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="test_clipboard.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="test_clipboard.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
\ No newline at end of file
#include "../../jlib/win32/wmi.h"
using namespace jlib::win32::wmi;
void out(const std::wstring& key, const std::wstring& value)
{
wprintf(L"%s\t%s\n", key.data(), value.data());
}
void err(HRESULT hr, const std::wstring& msg)
{
wprintf(L"Error 0x%08X, %s\n", hr, msg.data());
}
int main()
{
{
WmiBase wmi(L"root\\CIMV2", out, err);
wmi.prepare();
wmi.execute(L"SELECT SerialNumber FROM Win32_DiskDrive WHERE Index = 4");
wmi.execute(L"SELECT * FROM Win32_Processor");
}
{
WmiBase wmi(L"root\\CIMV2", out, err);
wmi.prepare();
wmi.execute(L"SELECT SerialNumber FROM Win32_DiskDrive WHERE Index = 4");
wmi.execute(L"SELECT * FROM Win32_Processor");
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{79A2C0A6-B8BB-406F-A732-C6300A611EC8}</ProjectGuid>
<RootNamespace>testwmi</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="test_wmi.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="test_wmi.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment