Russian Qt Forum
Октябрь 01, 2024, 02:47 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1] 2   Вниз
  Печать  
Автор Тема: Qt4 + WMI + VS2005  (Прочитано 23696 раз)
IGHOR
Крякер
****
Offline Offline

Сообщений: 390



Просмотр профиля WWW
« : Май 08, 2009, 00:36 »

Мне нужно использовать WMI в приложении Qt
Есть такой пример WMI для С++: http://msdn.microsoft.com/en-us/library/aa390423(VS.85).aspx
добавил его в пустой Qt проэкт созданный в Visual Studio 2005 Sp1
Код:
#include <QtGui/QApplication>

#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <Windows.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")

int main(int argc, char *argv[])
{
QApplication a(argc, argv);



    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x"
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------
    // Note: If you are using Windows 2000, you need to specify -
    // the default authentication credentials for a user by using
    // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
    // parameter of CoInitializeSecurity ------------------------

    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))
    {
        cout << "Failed to initialize security. Error code = 0x"
            << hex << hres << endl;
MessageBox(0,L"Filed1",L"",0);
        CoUninitialize();
        return 1;                    // Program has failed.
    }
   
    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
MessageBox(0,L"Filed1",L"",0);

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

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
         BSTR(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 (e.g. Kerberos)
         0,                       // Context object
         &pSvc                    // pointer to IWbemServices proxy
         );
   
    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x"
             << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    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))
    {
        cout << "Could not set proxy blanket. Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        BSTR("WQL"),
        BSTR("SELECT * FROM Win32_OperatingSystem"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &pEnumerator);
   
    if (FAILED(hres))
    {
        cout << "Query for operating system name failed."
            << " Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------
 
    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;
   
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        // Get the value of the Name property
        hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
        wcout << " OS Name : " << vtProp.bstrVal << endl;
MessageBox(0,vtProp.bstrVal,vtProp.bstrVal,0);
        VariantClear(&vtProp);
    }

    // Cleanup
    // ========
   
    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    pclsObj->Release();
    CoUninitialize();
getchar();
    return 0;   // Program successfully completed.

}
компилируеться прекрасно но здесь
Код:
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x"
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }
FAILED(hres) получаеться True..Failed to initialize COM library
создаю проэкт в чистом С++ компилирую - работает
Ранее не работал с СОМ обьектами.
Помогите пожалуйста разобраться.
Можно ли использовать WMI в Qt4 проэкте ?
« Последнее редактирование: Май 08, 2009, 00:41 от IGHOR » Записан
KADABRA
Гость
« Ответ #1 : Май 08, 2009, 01:15 »

http://support.microsoft.com/kb/824480
http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/e1bc9fe4-d985-473a-88f7-ef2ed47f77b3/
« Последнее редактирование: Май 08, 2009, 01:20 от KADABRA » Записан
IGHOR
Крякер
****
Offline Offline

Сообщений: 390



Просмотр профиля WWW
« Ответ #2 : Май 08, 2009, 02:06 »

KADABRA Спасибо все работает!
Записан
SABROG
Гость
« Ответ #3 : Май 08, 2009, 08:36 »

Главное, чтобы потом такого не возникало http://forum.vingrad.ru/forum/topic-256663.html
Записан
IGHOR
Крякер
****
Offline Offline

Сообщений: 390



Просмотр профиля WWW
« Ответ #4 : Май 10, 2009, 18:41 »

Главное, чтобы потом такого не возникало http://forum.vingrad.ru/forum/topic-256663.html

Протестировал, таких глюков нет, все прекрасно работает
Записан
Alchazar
Гость
« Ответ #5 : Январь 22, 2010, 16:02 »

Возможно ли использовать WMI в Qt без VS2005?
пробую такой код:
Код
C++ (Qt)
#define _WIN32_DCOM
#include <QtGui/QApplication>
#include <iostream>
using namespace std;
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qt_windows.h"
#include <QDebug>
#include <QSettings>
# pragma comment(lib, "wbemuuid.lib")
#include "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h"
 
//**************
...........
...........
 
HRESULT hres;
 
   // Initialize COM.
   hres = CoInitializeEx(0, COINIT_MULTITHREADED);
 
   if (FAILED(hres))
   {
       qDebug() << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
   }
 
   // Initialize
   hres =  CoInitializeSecurity(
       NULL,
       -1,      // COM negotiates service
       NULL,    // Authentication services
       NULL,    // Reserved
       RPC_C_AUTHN_LEVEL_DEFAULT,    // authentication
       RPC_C_IMP_LEVEL_IMPERSONATE,  // Impersonation
       NULL,             // Authentication info
       EOAC_NONE,        // Additional capabilities
       NULL              // Reserved
       );
 
 
   if (FAILED(hres))
   {
       qDebug() << "Failed to initialize security. "
           << "Error code = 0x"
           << hex << hres;
       CoUninitialize();
   }
 
   // Obtain the initial locator to Windows Management
   // on a particular host computer.
   IWbemLocator *pLoc = 0;
 
   hres = CoCreateInstance(
       CLSID_WbemLocator,
       0,
       CLSCTX_INPROC_SERVER,
       IID_IWbemLocator, (LPVOID *) &pLoc);
 
   if (FAILED(hres))
   {
       cout << "Failed to create IWbemLocator object. "
           << "Error code = 0x"
           << hex << hres << endl;
       CoUninitialize();
       return 1;       // Program has failed.
   }
 
   IWbemServices *pSvc = 0;
....
 

и получаю кучю ошибок:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h:21: wbemcli.h: No such file or directory
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h:22: wbemprov.h: No such file or directory
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h:23: wbemtran.h: No such file or directory
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h:24: wbemdisp.h: No such file or directory
mainwindow.cpp:90: error: `IWbemLocator' was not declared in this scope
mainwindow.cpp:98: error: `pLoc' was not declared in this scope

и так далее.

Я так понимаю сам Qt не имеет необходимых библиотек или тут дело не в этом?
Записан
niXman
Гость
« Ответ #6 : Январь 22, 2010, 16:30 »

Цитировать
Возможно ли использовать WMI в Qt без VS2005?
mingw?
тогда не понятно почему указан путь к микросовтостудийным хидерам?
Цитировать
#include "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WbemIdl.h"


Цитировать
# pragma comment(lib, "wbemuuid.lib")
это так же в мингве не работает.
Записан
niXman
Гость
« Ответ #7 : Январь 22, 2010, 16:47 »

вот нестандартно укомплектованный мингв: http://rghost.ru/873164
должно скомпилиться.
Записан
Alchazar
Гость
« Ответ #8 : Январь 22, 2010, 17:14 »

Скопировал новый mingw, поправил include
Код:
#define _WIN32_DCOM
#include <QtGui/QApplication>
#include <iostream>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qt_windows.h"
#include <QDebug>
#include <QSettings>
#include "Wbemidl.h"
Правильно теперь?

А в .pro файл надо что нибуть добавлять?

теперь такие ошибки(151шт):
c:\qt\2009.04\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/wbemcli.h:1737: error: '__RPC__in' has not been declared
c:\qt\2009.04\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/wbemcli.h:1737: error: expected ',' or '...' before 'strNamespace'
c:\qt\2009.04\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/wbemcli.h:1744: error: '__RPC__in_opt' has not been declared
c:\qt\2009.04\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/wbemcli.h:1744: error: expected ',' or '...' before '*' token
.....
и т.д.

Записан
niXman
Гость
« Ответ #9 : Январь 22, 2010, 18:08 »

в каталоге с микрософтстудийным СДК, найдите файл rpcsal.h
скопируйте его к хидерам мингва.
добавьте в свой код: #include <rpcsal.h>
и отпишитесь о результате.
Записан
Alchazar
Гость
« Ответ #10 : Январь 22, 2010, 20:55 »

попробовал, результат тот же  Обеспокоенный
Записан
niXman
Гость
« Ответ #11 : Январь 23, 2010, 01:21 »

точно такие-же ошибки?
Записан
Alchazar
Гость
« Ответ #12 : Январь 24, 2010, 18:45 »

да, те же ошибки, и то же количество ошибок
Записан
Alchazar
Гость
« Ответ #13 : Январь 25, 2010, 16:11 »

Пока что решил сделать dll-ку Visual Studio и использовать её в своей программе. Не уверен правильно ли это, но другого выхода я не придумал(.
Записан
kuzulis
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2812


Просмотр профиля
« Ответ #14 : Февраль 01, 2010, 14:16 »

Alchazar ,

мне тоже нужно использовать WMI... Хочу сделать универсальное решение путем подгрузки виндовой системной динамической библиотеки (библиотек).
Только проблема в том, что я не знаю какие библиотеки нужны + хочу чтобы компилилось как в VS, так и в стандартном minGW!

Люди, подскажите кто нибудь... Нужны идеи... Улыбающийся
Записан

ArchLinux x86_64 / Win10 64 bit
Страниц: [1] 2   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.085 секунд. Запросов: 23.