Tuesday, June 7, 2011

WMI Coding Example Using C++

The following Code example is one of many that can be found at:

http://www.planetmps.com/

            private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
             {
                String^ tempstr = "";
                String^ v = "";
                ManagementObjectSearcher^ mos = gcnew ManagementObjectSearcher("ApplicationLifetimeEvent");
                mos->Scope->Path->Path ="root\aspnet";
                ManagementObjectCollection^ moc = mos->Get();
                ManagementObjectCollection::ManagementObjectEnumerator^ mocEnum = moc->GetEnumerator();
                while (mocEnum->MoveNext())
                {
                    ManagementObject^ mo = dynamic_cast<ManagementObject^>(mocEnum->Current);
                    PropertyDataCollection^ propSet = mo->Properties;
                    PropertyDataCollection::PropertyDataEnumerator^ pEnum = propSet->GetEnumerator();
                    while (pEnum->MoveNext())
                    {
                        PropertyData^ prop = dynamic_cast<PropertyData^>(pEnum->Current);
                        if (prop->Value == nullptr)
                        {
                            tempstr = tempstr + "" + prop->Name + ":\n";
                        }
                        else
                        {
                            tempstr = tempstr + "" + prop->Name + ":" + GetValue(prop->Name, mo) + "\n";
                        }
                    }
                }
                MessageBox::Show(tempstr);
                tempstr = "";
            }
            private: System::String^ GetValue(String^ Name, ManagementObject^ mo)
            {
                String^ tstr = mo->GetText(TextFormat::Mof);
                Name = Name + " = ";
                int pos = 0;
                pos = tstr->IndexOf(Name);
                if (pos > -1)
                {
                    pos = pos + Name->Length;
                    tstr = tstr->Substring(pos, (tstr->Length - pos));
                    tstr = tstr->Substring(0, tstr->IndexOf(";"));
                    tstr = tstr->Replace("{", "");
                    tstr = tstr->Replace("}", "");
                    tstr = tstr->Replace("\x022", "");
                    tstr = tstr->Trim();
                    return tstr;
                }
                else
                {
                    return "";
                }
            }

No comments:

Post a Comment