0% found this document useful (0 votes)
87 views

Code Project Article WMICodeCreator and USB Serial Finder

This article summarizes a tool for working with WMI (Windows Management Instrumentation) called WMICodeCreator and demonstrates how to use WMI to find USB-to-serial port adapters connected to a system. It presents sample C# code generated by WMICodeCreator to search the WMI namespace and find any serial port adapters with "USB" in the instance name, then displays the associated COM port name. The article also introduces a debugging class called DBug that redirects console output to a form for easier debugging.

Uploaded by

Joel Bharath
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Code Project Article WMICodeCreator and USB Serial Finder

This article summarizes a tool for working with WMI (Windows Management Instrumentation) called WMICodeCreator and demonstrates how to use WMI to find USB-to-serial port adapters connected to a system. It presents sample C# code generated by WMICodeCreator to search the WMI namespace and find any serial port adapters with "USB" in the instance name, then displays the associated COM port name. The article also introduces a debugging class called DBug that redirects console output to a form for easier debugging.

Uploaded by

Joel Bharath
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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