As the title says I'd like to check if my microphone is muted. Or even better get an event if it gets muted/unmuted.
I tried to get some information form the internet. Turns out I simply don't get it. I found out about the "new" Audio Core API which gave me some ideas, sadly I did not find any c# code so I cant figure out how to use any of this.
With the following code I could get some information for my microphone, however nothing changes if I mute it.
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_SoundDevice");
ManagementObjectCollection objCollection = objSearcher.Get();
ManagementObject rodeMic = null;
foreach (ManagementObject obj in objCollection)
{
foreach (PropertyData property in obj.Properties)
{
if (property.Name == "DeviceID" && (string) property.Value == "USB\\VID_...")
{
rodeMic = obj;
}
}
}
if (rodeMic != null)
{
foreach (var property in rodeMic.Properties)
{
Console.Out.WriteLine(String.Format("{0}:{1}", property.Name, property.Value));
}
}
Related
Working but crashing is weird to say, but the hardware status gets printed in the console window but my application crash when i run this. I have it on the load of the form.
Error says: Object reference not set to an instance of an object
And here is the code:
// Hardware check
ManagementObjectSearcher deviceList =
new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
// Any results? There should be!
if (deviceList != null)
// Enumerate the devices
foreach (ManagementObject device in deviceList.Get())
{
// To make the example more simple,
string name = device.GetPropertyValue("Name").ToString();
string status = device.GetPropertyValue("Status").ToString();
// Uncomment these lines and use the "select * query" if you
// want a VERY verbose list
// foreach (PropertyData prop in device.Properties)
// Console.WriteLine( "\t" + prop.Name + ": " + prop.Value);
// More details on the valid properties:
//
Console.WriteLine("Device name: {0}", name);
Console.WriteLine("\tStatus: {0}", status);
// Part II, Evaluate the device status.
bool working = ((status == "OK") || (status == "Degraded")
|| (status == "Pred Fail"));
Console.WriteLine("\tWorking?: {0}", working);
}
So your problem when working with management objects is that all properties can return null and you need to account for this at all times as well as some other issues:
The searcher is not a list of devices nor will it ever contain one so you shouldn't call it deviceList.
You don't need to check the searcher for a value as all we're doing is initializing the class, it won't fail without an Exception.
You need to clean up after yourself by disposing of the management objects.
Since both Name and Status properties are strings anyway, you can cast them as such without calling .ToString() and use ?? string.Empty to replace null values with an empty string.
// Hardware check
using (ManagementObjectSearcher deviceSearcher = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity"))
using (ManagementObjectCollection devices = deviceSearcher.Get())
{
// Enumerate the devices
foreach (ManagementObject device in devices)
{
// To make the example more simple,
string name = (string)device.GetPropertyValue("Name") ?? string.Empty;
string status = (string)device.GetPropertyValue("Status") ?? string.Empty;
// Uncomment these lines and use the "select * query" if you
// want a VERY verbose list
// foreach (PropertyData prop in device.Properties)
// Console.WriteLine("\t{0}: {1}", prop.Name, prop.Value);
// More details on the valid properties:
//
Console.WriteLine("Device name: {0}", name);
Console.WriteLine("\tStatus: {0}", status);
// Part II, Evaluate the device status.
bool working = status == "OK" || status == "Degraded" || status == "Pred Fail";
Console.WriteLine("\tWorking?: {0}", working);
}
}
I'm using ManagementObjectSearcher to load all the printers available in the network. There all the printers are returned in a ManagementObjectCollection. Is there anyway to find out all the details returned?
I used the debugging of c# to preview the object but it does not show all the data in there. I want to know what is available other than Printers[Name],Printers[Local],Printers[Network]. Is there a possible way to do this?
Code
System.Management.ManagementScope objMS =
new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
System.Management.PropertyDataCollection pdc = Printers.Properties;
if (Convert.ToBoolean(Printers["Local"])) // LOCAL PRINTERS.
{
comboBox8.Items.Add(Printers["Name"]);
}
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
comboBox9.Items.Add(Printers["Name"]);
}
}
Generate strongly typed classes for Win32_Printer that will show you everything you need.
http://msdn.microsoft.com/en-us/library/2wkebaxa(v=vs.110).aspx - Mgmtclassgen.exe (Management Strongly Typed Class Generator)
You can enumerate the ManagementBaseObject.Properties property, and PropertyData.Qualifiers.
foreach (PropertyData property in properties)
{
Console.WriteLine(property.Name);
foreach (QualifierData q in property.Qualifiers)
{
if(q.Name.Equals("Description"))
{
Console.WriteLine(
processClass.GetPropertyQualifierValue(
property.Name, q.Name));
}
}
Console.WriteLine();
}
From MSDN
how can I turn off 'allow hybrid sleep' in advanced power setting? by c#
by manually: power options -> change Plan Settings -> change advanced power setting->
Sleep-> 'Allow hybrid sleep' -> plugged in: OFF
If you are targeting Windows 7/2008 Server then you can use WMI and the Win32_PowerSetting class. Below is code that does that. Make sure to add an assembly reference and using directive to System.Management.
private bool SetAllowHybridSleep(bool enabled)
{
//Machine to work on, "." for local
string RemotePC = ".";
//Set the namespace to the power namespace, used throughout the function
ManagementScope ms = new ManagementScope(#"\\" + RemotePC + #"\root\cimv2\power");
//Will hold each of our queries
ObjectQuery oq = null;
//Will hold the values of our power plan and the specific setting that we want to change
Guid PowerPlanInstanceId = Guid.Empty;
string PowerSettingInstanceId = null;
//Look for the specific setting that we want
oq = new ObjectQuery(string.Format("SELECT * FROM Win32_PowerSetting WHERE ElementName = 'Allow hybrid sleep'"));
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq))
{
ManagementObjectCollection results = mos.Get();
foreach (ManagementObject obj in results)
{
foreach (PropertyData p in obj.Properties)
{
if (p.Name == "InstanceID")
{
//This will give us a string with a GUID specific to our setting
PowerSettingInstanceId = p.Value.ToString();
break;
}
}
}
}
//Sanity check
if (string.IsNullOrEmpty(PowerSettingInstanceId))
{
Console.WriteLine("System does not support hybrid sleep");
return false;
}
//Look for the active power scheme
oq = new ObjectQuery("SELECT * FROM Win32_PowerPlan WHERE IsActive=True");
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq))
{
ManagementObjectCollection results = mos.Get();
foreach (ManagementObject obj in results)
{
foreach (PropertyData p in obj.Properties)
{
if (p.Name == "InstanceID")
{
//The instance contains a string with a GUID inside of it, use the code below to get the GUID by itself
if (!Guid.TryParse(System.Text.RegularExpressions.Regex.Match(p.Value.ToString(), #"\{[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}\}").Value, out PowerPlanInstanceId))
{
Console.WriteLine("Could not find active power plan");
return false;
}
break;
}
}
}
}
//Now we need to update the actual power setting in the active plan
//Get all power schemes for the target setting
oq = new ObjectQuery(string.Format("ASSOCIATORS OF {{Win32_PowerSetting.InstanceID=\"{0}\"}} WHERE ResultClass = Win32_PowerSettingDataIndex", PowerSettingInstanceId.Replace(#"\", #"\\")));
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq))
{
ManagementObjectCollection results = mos.Get();
foreach (ManagementObject obj in results)
{
foreach (PropertyData p in obj.Properties)
{
//See if the current scheme is the current setting. This will happen twice, once for AC and once for DC
if (p.Name == "InstanceID" && p.Value.ToString().Contains(PowerPlanInstanceId.ToString()))
{
//Change the value of the current setting
obj.SetPropertyValue("SettingIndexValue", (enabled ? "1" : "0"));
obj.Put();
break;
}
}
}
}
return true;
}
Using procmon, I managed to work out that the following registry key is responsible for it on my machine.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\94ac6d29-73ce-41a6-809f-6363ba21b47e
You'll probably have to do some research on your machine to see how it works for you.
You can also call on the powercfg utility to do this. Each power setting is identified by three things:
GUID of power profile
GUID of profile subgroup
GUID of setting
You can use powercfg -QUERY to produce a full list of values.
Once you've got the GUID of the profile you want to edit, the GUID of the subgroup (in this case the Sleep subgroup) and the GUID of the setting (Allow Hybrid Sleep) you can use either powercfg -SETACVALUEINDEX for plugged in or powercfg -SETDCVALUEINDEX for on battery to set the value.
In my case (Win7 Ultimate x64) you can turn it off using:
powercfg -SETACVALUEINDEX 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 1
This translates to the AcSettingIndex value in:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\94AC6D29-73CE-41A6-809F-6363BA21B47E\DefaultPowerSchemeValues\381b4222-f694-41f0-9685-ff5bb260df2e
I am trying to get the printer status of a PointOfSale printer using the following code:
Hashtable properties = new Hashtable();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win2_Printer");
foreach (ManagementObject obj in searcher.Get()) {
if (obj["name"].ToString() == printerName) {
foreach (PropertyData data in obj.Properties) {
if(data.Name.ToLower() = "printerstatus") {
int printerStatus = Convert.ToInt32(data.Value);
}
}
}
}
Problem is, the status is either 3 (idle) or 4(printing), even when unplugged or the paper is out.
I have read a lot of posts with this same issue, but have not found an answer. Is this correct? How else would I check the status? Any help is appreciated.
What Brand of printer are you using?
Sometimes the Brand will have a specific command you can send to query the status.
When I use this function in c#, it is able to get drive letter but, when I remove the USB stick and test this function, it doesnt go to the Exception.
So could someone help me with where I am going wrong in the function code?
public void GetDriveLetter()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition"))
{
foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
{
// writer.WriteLine("{0}" + "\\", c["Name"].ToString()); // here it will print drive letter
usbDriveLetter = String.Format("{0}" + "\\", c["Name"].ToString());
}
}
}
}
catch (ManagementException e)
{
MessageBox.Show(e.StackTrace);
}
//CombinedPath = System.IO.Path.Combine(usbDriveLetter.Trim(), path2.Trim());
}
You Method wont throw an Exception as nothing is breaking. If you want to throw and Exception when no usb's are found then you can do this.
if (searcher.Get().Count == 0)
throw new ApplicationException("No Usb drives connected");
Update: will return true if any USB device is found
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
return (from ManagementObject queryObj in searcher.Get()
from ManagementObject b in queryObj.GetRelated("Win32_DiskPartition")
select b).Select(b => b.GetRelated("Win32_LogicalDisk").Count > 0).FirstOrDefault();
Probably it does not go to the exception because as you have removed the USB stick, the device is not even listed and no exception happens.
Why do you want to generate an exception at all in case the usb stick is not plugged in?
also, you could eventually have better luck replacing the specific exception in the catch definition with a simple Exception object but I don't think this is the issue, as I said above probably no exception is thrown simply because you don^t list anymore the removed device.