Using array to display Win32_SystemDriver query results in C# - c#

So I am trying to get Description information from Win32_SystemDriver into a RichTextBox, but I am not able to do that because it only displays the last result from the query. As you can see bellow I tried to build an array but it does not work.
ObjectQuery query8 = new ObjectQuery(
"SELECT * FROM Win32_SystemDriver");
ManagementObjectSearcher searcher8 =
new ManagementObjectSearcher(scope, query8);
foreach (ManagementObject queryObj in searcher8.Get())
{
string[] arrTeamMembers = new string[] { queryObj["Description"].ToString() };
foreach (var item in arrTeamMembers)
{
richTextBox1.Text = item;
}
}
Do you have any ideia how can I display all the info listing into the RichTextBox?

Try following :
List<string> arrTeamMembers = new List<string>();
foreach (ManagementObject queryObj in searcher8.Get())
{
arrTeamMembers.Add(queryObj["Description"].ToString());
}
richTextBox1.Text = string.Join(",", arrTeamMembers);

Your approach is ok. There is one thing which you missed: richTextBox1.Text is a so-called property that stores a string. Now the reason why it shows you only the last driver is that you set this property to a new value for each driver you have in your array. So for the first driver it sets it to "driverA" and for the second to "driverB". What you are looking for is the += operator --> richTextBox1.Text += item;. If you want to add spaces between the drivers you can do something like richTextBox1.Text += $" {item}";. This way you have a leading whitespace but formating is personal preference.

Please note that ManagementObjectSearcher are IDisposable and therefore should be disposed.
ObjectQuery query8 = new ObjectQuery("SELECT * FROM Win32_SystemDriver");
using (ManagementObjectSearcher searcher8 = new ManagementObjectSearcher(scope, query8))
{
List<string> arrTeamMembers = new List<string>();
foreach (ManagementObject queryObj in searcher8.Get())
{
arrTeamMembers.Add(queryObj["Description"].ToString());
}
richTextBox1.Text = string.Join(Environment.NewLine, arrTeamMembers);
}

var query8 = new ObjectQuery("SELECT * FROM Win32_SystemDriver");
var searcher8 = new ManagementObjectSearcher(scope, query8);
var strbuilder = new StringBuilder();
foreach (var queryObj in searcher8.Get())
strbuilder.AppendLine($"{queryObj["Description"].ToString()}");
richTextBox1.Text = strbuilder.ToString();

Related

How to get properties in VideoModeDescriptor through WmiMonitorListedSupportedSourceModes?

I'm trying to get the Monitor properties in C#. I use the WMI to get the information I need.
Currently I can get correct PNPID from Win32_DesktopMonitor and compare with the result of InstanceName from WmiMonitorListedSupportedSourceModes.
Then I want to get detail information of the monitor by VideoModeDescriptor. Here are my codes below, but I always get the fail as "invalid query" of scherDM2c.Get().
May I know what kind of mistake I made?
private void MonitorBox_SelectedIndexChanged(object sender, EventArgs e)
{
ManagementObjectSearcher searcherM = new ManagementObjectSearcher($"SELECT * FROM Win32_DesktopMonitor Where Name Like '%{MonitorBox.Text}%'");
foreach (ManagementObject wmi in searcherM.Get())
{
dMaker.Text = wmi.GetPropertyValue("MonitorManufacturer").ToString();
dID.Text = wmi.GetPropertyValue("PNPDeviceID").ToString();
ManagementObjectSearcher searcherDM2a = new ManagementObjectSearcher("root\\wmi", "SELECT * FROM WmiMonitorListedSupportedSourceModes");
foreach (ManagementObject sbu_wmi in searcherDM2a.Get())
{
string WMIID = sbu_wmi.GetPropertyValue("InstanceName").ToString();
if (WMIID.ToUpper().Contains(dID.Text.ToUpper()))
{
ManagementObjectSearcher scherDM2c = new ManagementObjectSearcher("root\\wmi", $"SELECT * FROM WmiMonitorListedSupportedSourceModes Where InstanceName Like %{WMIID}%");
//ManagementObjectCollection MColl = scherDM2c.Get();
foreach (ManagementObject ModeList in scherDM2c.Get())
{
listBox1.Items.Add(ModeList.GetPropertyValue("HorizontalActivePixels").ToString());
}
/*listBox1.Items.Add(sbu_wmi.GetPropertyValue("PreferredMonitorSourceModeIndex").ToString());
var i = sbu_wmi.GetPropertyValue("PreferredMonitorSourceModeIndex").ToString();
listBox1.Items.Add(sbu_wmi.GetPropertyValue("MonitorSourceModes").ToString());*/
}
}
/*listBox1.Items.Add(wmi.GetPropertyValue("CreationClassName").ToString());
listBox1.Items.Add(wmi.GetPropertyValue("Caption").ToString());
listBox1.Items.Add(wmi.GetPropertyValue("MonitorType").ToString());*/
}
}
Try this,You forgot to add ''
ManagementObjectSearcher scherDM2c = new ManagementObjectSearcher("root\\wmi", $"SELECT * FROM WmiMonitorListedSupportedSourceModes Where InstanceName Like '%{WMIID}%'");

Get Parent property of network adapter device from c#

I need to get the Parent property of network adapter device from c# program
Please find the image here
Tried below code but the property "Parent" is not available
List mappingIpDeviceIds = new List();
Console.WriteLine("Reading Id and IP address...");
ManagementObjectSearcher adapters = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus = 2");
foreach (ManagementObject item in adapters.Get())
{
foreach (ManagementObject setting in item.GetRelated("Win32_NetworkAdapterConfiguration"))
{
var relationships = setting.GetRelationships();
var name = setting["Caption"].ToString();
string[] defaultIPGateway = (string[])setting.GetPropertyValue("DefaultIPGateway");
string[] compterips = (string[])setting.GetPropertyValue("IPAddress");
string dhcpserver = (string)setting.GetPropertyValue("DHCPServer");
foreach (ManagementObject win32PnPEntity in item.GetRelated("Win32_PnPEntity"))
{
var x = win32PnPEntity.Properties;
foreach (var prop in x)
{
Console.WriteLine("::: PROPERTY NAME ::: " + prop.Name);
Console.WriteLine("::: PROPERTY VALUE ::: " + prop.Value);
}
}
MappingIpDeviceId mappingIpDeviceId = new MappingIpDeviceId();
string deviceid = (string)item.GetPropertyValue("PNPDeviceID");
string deviceid1 = (string)item.GetPropertyValue("ProductName");
string[] devicenames = deviceid.Split(new Char[] { '\\' });
foreach (string dn in devicenames)
{
mappingIpDeviceId.OWLIP = dhcpserver;
mappingIpDeviceId.ComputerIP = compterips[0];
mappingIpDeviceId.DeviceId = dn;
mappingIpDeviceIds.Add(mappingIpDeviceId);
}
}
}
There are two ways you can refer to:
Using PowerShell command Get-PnpDeviceProperty: Get-PnpDeviceProperty -KeyName 'DEVPKEY_Device_Parent' -InstanceId 'xxxxxxxxxxxxxxxx'
Use CM_Get_Parent. "Determining the Parent of a Device".

How to search in a List by first item

Here is my list:
public static List<Tuple<string, string>> hardDiskInfo(string hostname)
{
var hardDiskInfo = new List<Tuple<string, string>>();
ManagementScope Scope;
if (!hostname.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = Properties.Settings.Default.uName;
Conn.Password = Properties.Settings.Default.pWord;
Conn.Authority = "ntlmdomain:" + Properties.Settings.Default.doMain;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), null);
Scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3 OR DriveType = 4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject mo in queryCollection)
{
foreach (PropertyData p in mo.Properties)
{
if (p.Value != null)
{
hardDiskInfo.Add(new Tuple<string, string>(p.Name.ToString(), p.Value.ToString()));
}
}
}
return hardDiskInfo;
}
I'd like to know how to get the second p.Value of the p.Name after calling it:
hardDiskInfo(inputText.Text);
For example the value of the "FreeSpace" which is defined in Win32_LogicalDisk.
I'm having more Win32_ queries so knowing this will help me handling all of them and I'll be a happy panda.
Thank you.
Are the Names unique?
You might try:
var values = hardDiskInfo(inputText.Text);
// Get the first or default which matches "FreeSpace".
var freeSpaceInfo = values.FirstOrDefault(item => item.Item1 == "FreeSpace");
// If it was found,
if(freeSpaceInfo != null)
{
MessageBox.Show($"FreeSpace: {freeSpaceInfo.Item2}");
}
Next step: Use a Dictionary<string, string> which is much better.

Using ManagementObjectSearcher to query Win32_PnPEntity comes back empty

OK, so this drives me nuts.
The code below worked just fine in Windows 7 with .NET 3.5.
In Windows 8.1 and .NET 4.5.1 I get an empty result, but using the WMI Code Creator I can get the results.
I cannot find anything about this online.
I want to get the friendly names of any COM ports, e.g. "Communications Port (COM1)".
Just using System.IO.Ports.SerialPort.GetPortNames() wont do.
I really hope someone know how to do this. Thanks!
using System;
using System.Collections.Generic;
using System.Management;
namespace OakHub
{
public class SerialMgmt
{
static public List<String> GetCOMDevices()
{
List<String> list = new List<String>();
ManagementScope scope = new ManagementScope(#"\\" + Environment.MachineName + #"\root\CIMV2");
SelectQuery sq = new SelectQuery("SELECT Caption FROM Win32_PnPEntity");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
String name = mo.ToString();
if (name.ToString().Contains("(COM"))
{
list.Add(name);
}
}
return list;
}
}
}
First of all I dont know why this code is even working for you (with .Net 3.5).
You just selected the property Caption. (Use * to select all, if needed)
I think you want the name of the Win32_PnPEntity-Devices, you cant get it with this line of code
String name = mo.ToString();
Because the Name is a property. You First have to load the Property with the WMI-String :
SELECT Name,Caption FROM Win32_PnPEntity //Get Name and Caption Property
or
SELECT * FROM Win32_PnPEntity //Load all the Propertys of that WMI-Obj
And than you have to check if value is null else --> return the value
Code:
public List<String> GetLocalCOMDevices()
{
List<String> list = new List<String>();
ManagementScope scope = new ManagementScope(#"\\" + Environment.MachineName + #"\root\CIMV2");
SelectQuery sq = new SelectQuery("SELECT Name,Caption FROM Win32_PnPEntity");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
object propName = mo.Properties["Name"].Value;
if (propName == null) { continue; }
list.Add(propName.ToString());
}
return list;
}

How to query GetMonitorBrightness from C#

How does GetMonitorBrightness http://msdn.microsoft.com/en-us/library/ms775205.aspx work? Can someone give me an actual working implementation calling this code in C#?
I'm trying to retrieve the allowed brightness levels my laptop supports.
I have the following working code that sets the brightness from 1 to ~150. But I'm looking for the allowed input values (min max values).
static void SetBrightness(byte targetBrightness)
{
ManagementScope scope = new ManagementScope("root\\WMI");
SelectQuery query = new SelectQuery("WmiMonitorBrightnessMethods");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection objectCollection = searcher.Get())
{
foreach (ManagementObject mObj in objectCollection)
{
mObj.InvokeMethod("WmiSetBrightness",
new Object[] { UInt32.MaxValue, targetBrightness });
break;
}
}
}
}
While using Interop should be possible this function is also available through WMI. Changing my original code a bit resulted in the following code that should work:
ManagementScope scope;
SelectQuery query;
scope = new ManagementScope("root\\WMI");
query = new SelectQuery("SELECT * FROM WmiMonitorBrightness");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection objectCollection = searcher.Get())
{
foreach (ManagementObject mObj in objectCollection)
{
Console.WriteLine(mObj.ClassPath);
foreach (var item in mObj.Properties)
{
Console.WriteLine(item.Name + " " +item.Value.ToString());
if(item.Name =="CurrentBrightness")
//Do something with CurrentBrightness
}
}
}
}
Now I'm really curious how to handle 'special' cases like non laptop Screen's and if they implement any way to influence brightness.
The function has an output of the minimum and maximum values:
LPDWORD pdwMinimumBrightness=NULL;
LPDWORD pdwMaximumBrightness=NULL;
HANDLE pmh = pPhysicalMonitors[0].hPhysicalMonitor;
GetMonitorBrightness(pmh, pdwMinimumBrightness, pdwMaximumBrightness);
This is assuming that you want the values for the first monitor.

Categories

Resources