Работа с реестром на C/C++

Все о микроконтроллерах: AVR, PIC, STM8, STM32, Arduino, Altera, Xilinx, все что угодно. Этот раздел для всего что клацает байтиками.
Vitalik
Сообщения: 39

Сообщение Vitalik » 16 июн 2014, 15:43

Добрый день. Предлагаю в этой теме обсуждать вопросы, связанные с реестром Windows.
Вот мой вопрос:
Я пишу программу-терминал для работы с com-портом и у меня возникли трудности с перечислением портов, доступных в системе. Я посмотрел разные форумы и msdn. Все сводится к вот такому коду:

Код: Выделить всё

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

#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 16383

using namespace std;

void QueryKey(HKEY hKey)
{
    TCHAR    achKey[MAX_KEY_LENGTH];   // buffer for subkey name
    DWORD    cbName;                   // size of name string
    TCHAR    achClass[MAX_PATH] = TEXT("");  // buffer for class name
    DWORD    cchClassName = MAX_PATH;  // size of class string
    DWORD    cSubKeys=0;               // number of subkeys
    DWORD    cbMaxSubKey;              // longest subkey size
    DWORD    cchMaxClass;              // longest class string
    DWORD    cValues;              // number of values for key
    DWORD    cchMaxValue;          // longest value name
    DWORD    cbMaxValueData;       // longest value data
    DWORD    cbSecurityDescriptor; // size of security descriptor
    FILETIME ftLastWriteTime;      // last write time

    DWORD i, retCode;

    TCHAR  achValue[MAX_VALUE_NAME];
    DWORD cchValue = MAX_VALUE_NAME;

    // Get the class name and the value count.
    retCode = RegQueryInfoKey(
                  hKey,                    // key handle
                  achClass,                // buffer for class name
                  &cchClassName,           // size of class string
                  NULL,                    // reserved
                  &cSubKeys,               // number of subkeys
                  &cbMaxSubKey,            // longest subkey size
                  &cchMaxClass,            // longest class string
                  &cValues,                // number of values for this key
                  &cchMaxValue,            // longest value name
                  &cbMaxValueData,         // longest value data
                  &cbSecurityDescriptor,   // security descriptor
                  &ftLastWriteTime);       // last write time

    // Enumerate the subkeys, until RegEnumKeyEx fails.

    if (cSubKeys)
    {
        cout << "\nNumber of subkeys: " << cSubKeys << endl;

        for (i=0; i<cSubKeys; i++)
        {
            cbName = MAX_KEY_LENGTH;
            retCode = RegEnumKeyEx(hKey, i,
                                   achKey,
                                   &cbName,
                                   NULL,
                                   NULL,
                                   NULL,
                                   &ftLastWriteTime);
            if (retCode == ERROR_SUCCESS)
            {
                cout << "achKey: " << achKey << endl;
            }
        }
    }

    // Enumerate the key values.

    if (cValues)
    {
        cout << "Number of values: " << cValues << endl;

        for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++)
        {
            cchValue = MAX_VALUE_NAME;
            achValue[0] = '\0';
            retCode = RegEnumValue(hKey, i,
                                   achValue,
                                   &cchValue,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL);

            if (retCode == ERROR_SUCCESS )
            {
                cout << "achValue: " << achValue << endl;
            }
        }
    }
}

int main(void)
{
    HKEY hTestKey;

    if( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
                      TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
                      0,
                      KEY_READ,
                      &hTestKey) == ERROR_SUCCESS
      )
    {
        QueryKey(hTestKey);
    }

    RegCloseKey(hTestKey);
    return 0;
}

(Код из msdn)
Вот картинка, зеленым я выделил то, что выводит программа. Красным - то, что необходимо прочитать в программе.

Изображение
Собственно вопрос: как прочитать то, что выделено красным?

gylka
Сообщения: 14
Откуда: Киев

Сообщение gylka » 18 июн 2014, 10:34


Vitalik
Сообщения: 39

Сообщение Vitalik » 19 июн 2014, 17:26

Спасибо за помощь. Нашел решение в старой версии библиотеки QSerialDevice. Вот мой рабочий код:

Код: Выделить всё

void ListOfPorts(void)
{
    DWORD i = 0;                                //номер ключа
    DWORD keyType = 0;                     //тип ключа
    const int MAX_KEY_LEN = 256;            //максимальная длина имени или знчения ключа
    char keyName[MAX_KEY_LEN];               //имя ключа
    char keyValue[MAX_KEY_LEN];               //значение ключа
    DWORD keyNameLength = sizeof(keyName);      //размер имени ключа в байтах
    DWORD keyValueLength = sizeof(keyValue);   //размер значения ключа в байтах
    HKEY hkey = 0;                        //дескриптор ключа

    string devices;                             //переменная со значение ключа

    RegOpenKeyExA(HKEY_LOCAL_MACHINE,
                  TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
                  0,
                  KEY_READ,
                  &hkey);

    while(RegEnumValueA(hkey, i++, keyName, &keyNameLength, 0, &keyType,
                        (BYTE *)keyValue, &keyValueLength) == ERROR_SUCCESS)
    {
        if(keyType == REG_SZ)
        {
            devices = keyValue;
        }
        keyNameLength = sizeof(keyName);
        keyValueLength = sizeof(keyValue);
        cout << devices << endl;
    }
    RegCloseKey(hkey);
}

yaachii
Сообщения: 39981

Сообщение yaachii » 19 апр 2025, 13:14


yaachii
Сообщения: 39981

Сообщение yaachii » 02 май 2025, 13:35

http://audiobookkeeper.ruhttp://cottagenet.ruhttp://eyesvision.ruhttp://eyesvisions.comhttp://factoringfee.ruhttp://filmzones.ruhttp://gadwall.ruhttp://gaffertape.ruhttp://gageboard.ruhttp://gagrule.ruhttp://gallduct.ruhttp://galvanometric.ruhttp://gangforeman.ruhttp://gangwayplatform.ruhttp://garbagechute.ruhttp://gardeningleave.ruhttp://gascautery.ruhttp://gashbucket.ruhttp://gasreturn.ruhttp://gatedsweep.ruhttp://gaugemodel.ruhttp://gaussianfilter.ruhttp://gearpitchdiameter.ru
http://geartreating.ruhttp://generalizedanalysis.ruhttp://generalprovisions.ruhttp://geophysicalprobe.ruhttp://geriatricnurse.ruhttp://getintoaflap.ruhttp://getthebounce.ruhttp://habeascorpus.ruhttp://habituate.ruhttp://hackedbolt.ruhttp://hackworker.ruhttp://hadronicannihilation.ruhttp://haemagglutinin.ruhttp://hailsquall.ruhttp://hairysphere.ruhttp://halforderfringe.ruhttp://halfsiblings.ruhttp://hallofresidence.ruhttp://haltstate.ruhttp://handcoding.ruhttp://handportedhead.ruhttp://handradar.ruhttp://handsfreetelephone.ru
http://hangonpart.ruhttp://haphazardwinding.ruhttp://hardalloyteeth.ruhttp://hardasiron.ruhttp://hardenedconcrete.ruhttp://harmonicinteraction.ruhttp://hartlaubgoose.ruhttp://hatchholddown.ruhttp://haveafinetime.ruhttp://hazardousatmosphere.ruhttp://headregulator.ruhttp://heartofgold.ruhttp://heatageingresistance.ruhttp://heatinggas.ruhttp://heavydutymetalcutting.ruhttp://jacketedwall.ruhttp://japanesecedar.ruhttp://jibtypecrane.ruhttp://jobabandonment.ruhttp://jobstress.ruhttp://jogformation.ruhttp://jointcapsule.ruhttp://jointsealingmaterial.ru
http://journallubricator.ruhttp://juicecatcher.ruhttp://junctionofchannels.ruhttp://justiciablehomicide.ruhttp://juxtapositiontwin.ruhttp://kaposidisease.ruhttp://keepagoodoffing.ruhttp://keepsmthinhand.ruhttp://kentishglory.ruhttp://kerbweight.ruhttp://kerrrotation.ruhttp://keymanassurance.ruhttp://keyserum.ruhttp://kickplate.ruhttp://killthefattedcalf.ruhttp://kilowattsecond.ruhttp://kingweakfish.ruhttp://kinozones.ruhttp://kleinbottle.ruhttp://kneejoint.ruhttp://knifesethouse.ruhttp://knockonatom.ruhttp://knowledgestate.ru
http://kondoferromagnet.ruhttp://labeledgraph.ruhttp://laborracket.ruhttp://labourearnings.ruhttp://labourleasing.ruhttp://laburnumtree.ruhttp://lacingcourse.ruhttp://lacrimalpoint.ruhttp://lactogenicfactor.ruhttp://lacunarycoefficient.ruhttp://ladletreatediron.ruhttp://laggingload.ruhttp://laissezaller.ruhttp://lambdatransition.ruhttp://laminatedmaterial.ruhttp://lammasshoot.ruhttp://lamphouse.ruhttp://lancecorporal.ruhttp://lancingdie.ruhttp://landingdoor.ruhttp://landmarksensor.ruhttp://landreform.ruhttp://landuseratio.ru
http://languagelaboratory.ruhttp://largeheart.ruhttp://lasercalibration.ruhttp://laserlens.ruhttp://laserpulse.ruhttp://laterevent.ruhttp://latrinesergeant.ruhttp://layabout.ruhttp://leadcoating.ruhttp://leadingfirm.ruhttp://learningcurve.ruhttp://leaveword.ruhttp://machinesensible.ruhttp://magneticequator.ruhttp://magnetotelluricfield.ruhttp://mailinghouse.ruhttp://majorconcern.ruhttp://mammasdarling.ruhttp://managerialstaff.ruhttp://manipulatinghand.ruhttp://manualchoke.ruhttp://medinfobooks.ruhttp://mp3lists.ru
http://nameresolution.ruhttp://naphtheneseries.ruhttp://narrowmouthed.ruhttp://nationalcensus.ruhttp://naturalfunctor.ruhttp://navelseed.ruhttp://neatplaster.ruhttp://necroticcaries.ruhttp://negativefibration.ruhttp://neighbouringrights.ruhttp://objectmodule.ruhttp://observationballoon.ruhttp://obstructivepatent.ruhttp://oceanmining.ruhttp://octupolephonon.ruhttp://offlinesystem.ruhttp://offsetholder.ruhttp://olibanumresinoid.ruhttp://onesticket.ruhttp://packedspheres.ruhttp://pagingterminal.ruhttp://palatinebones.ruhttp://palmberry.ru
http://papercoating.ruhttp://paraconvexgroup.ruhttp://parasolmonoplane.ruhttp://parkingbrake.ruhttp://partfamily.ruhttp://partialmajorant.ruhttp://quadrupleworm.ruhttp://qualitybooster.ruhttp://quasimoney.ruhttp://quenchedspark.ruhttp://quodrecuperet.ruhttp://rabbetledge.ruhttp://radialchaser.ruhttp://radiationestimator.ruhttp://railwaybridge.ruhttp://randomcoloration.ruhttp://rapidgrowth.ruhttp://rattlesnakemaster.ruhttp://reachthroughregion.ruhttp://readingmagnifier.ruhttp://rearchain.ruhttp://recessioncone.ruhttp://recordedassignment.ru
http://rectifiersubstation.ruhttp://redemptionvalue.ruhttp://reducingflange.ruhttp://referenceantigen.ruhttp://regeneratedprotein.ruhttp://reinvestmentplan.ruhttp://safedrilling.ruhttp://sagprofile.ruhttp://salestypelease.ruhttp://samplinginterval.ruhttp://satellitehydrology.ruhttp://scarcecommodity.ruhttp://scrapermat.ruhttp://screwingunit.ruhttp://seawaterpump.ruhttp://secondaryblock.ruhttp://secularclergy.ruhttp://seismicefficiency.ruhttp://selectivediffuser.ruhttp://semiasphalticflux.ruhttp://semifinishmachining.ruhttp://spicetrade.ruhttp://spysale.ru
http://stungun.ruhttp://tacticaldiameter.ruhttp://tailstockcenter.ruhttp://tamecurve.ruhttp://tapecorrection.ruhttp://tappingchuck.ruhttp://taskreasoning.ruhttp://technicalgrade.ruhttp://telangiectaticlipoma.ruhttp://telescopicdamper.ruhttp://temperateclimate.ruhttp://temperedmeasure.ruhttp://tenementbuilding.rutuchkashttp://ultramaficrock.ruhttp://ultraviolettesting.ru

Вернуться в «Микроконтроллеры и ПЛИС»



Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 4 гостя