You are on page 1of 3

CodeProjectArticleAusefulWMItool& howtofindUSBtoSerialadaptors

Intro
Thisarticlehastwomainpurposes: ToillustrateandadvertiseausefultoolforWMI(WMICodeCreator) TodemonstratesomeWMIcodetofindUSBSerial/COMportadaptorsonthesystem

HoweveritwillnotcoveranygroundonWMI,neitherwillitshowyouhowtousetheserialport,therearemany usefularticlesalreadyavailableforthis.ThisarticleisalsomyfirstposttoCodeProjectwhichismyfavourite resourceforlearninghowtocreatecoolnewwidgets,sotryingtogivesomethingbacktothisgreatcommunity.

Background
Ihaveaprojectwhichcontrolsprojectorstoswitchthemonoroffviatheserialport(goodoldRS232).ThePC controllingtheprojectorislocatedinaserverroomalongwayfromtheprojector.TheyarebothlinkedbyaKVM extenderwhichsqueezesaVGAsignalandaUSBsignaloverasingleCAT5Ethernetcableupto120maway. SoIhavetouseaUSBtoSerialadaptortotalktotheprojector.Theproblemwiththeseadaptorsaretheyare virtualportsandtheygetassignedarandomCOMportnamesuchasCOM7.Alsotheysometimeshaveatendency towanderandchangetheirportname,requiringconstantmaintenancetolocatetheprojector.Icannotrelyonthe .NetserialportgetnamesasitwillreturnnonUSBCOMportsaswell.AstherewillonlybeoneadaptorperPCit makessensetosearchforit,usingWMI.

WMICodeCreator
IhaveusedWindowsManagementInstrumentationpreviouslytofindMACaddressesanddiskdrives.Tolocate somethingintheWMIuniversesoundeddauntingtome.Punchinginallthekeywordsintogoogledidntgetme veryfar,untilsomeonementionedWMICodeCreatorontheMSDNforumsPlaywithWMIusingthistoolitsaid. Itcanbeusedtosearchthenamespaces,classes,properties,methods,qualifiers.Youcanquerythedatabase, receiveaneventorjustbrowsethenamespace.ItevengivesyoudescriptionswherepossibleThe MaximumBaudRatepropertyindicatesthemaximum....Whenyoufoundwhatyouwerelookingforselectthecode languageyouwant(e.g.C#)anditwillgeneratethecodeneededforyourquery.

USBtoSerialAdaptors
Ihaveusedserialadaptorsinthepast,IhavealwayshadproblemswhenpluggingtheminadifferentUSBportthey changetheirname,e.g.fromCOM5toCOM6. Thisisatypicaladaptorfromprolific:

IhaveattachedthesourcecodeforaVS2005C#projectcalledWMITestBed.ItscalledthisasIimagineIwillneedit totestmoreWMIcodeinthefuture,notjustboringoldserialports.IthasaworkingdemonstrationofaUSBSerial finderusinglittlemorethanthecopypastedcodefromtheWMIutility.Usethistogetyoustarteditsveryeasyto messaboutwithyourowncodehere.


//Below is code pasted from WMICodeCreator try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName");

foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("-----------------------------------"); Console.WriteLine("MSSerial_PortName instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]); Console.WriteLine("-----------------------------------"); Console.WriteLine("MSSerial_PortName instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("PortName: {0}", queryObj["PortName"]);

//If the serial port's instance name contains USB it must be a USB to serial device if (queryObj["InstanceName"].ToString().Contains("USB")) { Console.WriteLine(queryObj["PortName"] + " is a USB to SERIAL adapter/converter"); } } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); }

Hereswhatitdoes:

Incidentals
TooutputtheresultsofthecodeIhaveaClasscalledDBug.JustasthenamesuggestsIuseitfordebugging.Ifind theConsoleintheIDEbecomesfartoomessywhendebuggingmultipleformssoIcreatedthis.Theoutputcanbe redirectedtoanyformwhichmakesitmoreflexibleandeasiertounderstand.IhaveoverriddenConsoleand WriteLinesothatalltheoutputgoestotheform,ifyougetanyambiguouscompileerrorssimplycommentoutthis Classandwatchyouroutputwindowinstead.

Dontforget
Ifyoucreateyourownproject,dontforgettoaddthereferencetoSystem.Managmentoritwontcompile. Hopeithelps! Surf_uk

You might also like