static byte[] QueryAvailableBrightnessLevels() { byte[] BrightnessLevels = new byte[0]; System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightness"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); try { System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { BrightnessLevels = (byte[])ManObject.GetPropertyValue("Level"); break; } ManObjC.Dispose(); ManObjS.Dispose(); } catch (Exception VideoException) { MessageBox.Show("Unable to get available brightness levels. The video card may not support this feature or the driver is not installed. Error: " + VideoException.Message, "BControl", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(BrightnessLevels); }
//array of valid brightness values in percent static byte[] GetBrightnessLevels() { //define scope (namespace) System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness"); //output current brightness System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); byte[] BrightnessLevels = new byte[0]; try { System.Management.ManagementObjectCollection moc = mos.Get(); //store result foreach (System.Management.ManagementObject o in moc) { BrightnessLevels = (byte[])o.GetPropertyValue("Level"); break; //only work on the first object } moc.Dispose(); mos.Dispose(); } catch (Exception) { MessageBox.Show("Sorry, Your System does not support this brightness control..."); } return(BrightnessLevels); }
//get the actual percentage of brightness static int GetBrightness() { //define scope (namespace) System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness"); //output current brightness System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); System.Management.ManagementObjectCollection moc = mos.Get(); //store result byte curBrightness = 0; foreach (System.Management.ManagementObject o in moc) { curBrightness = (byte)o.GetPropertyValue("CurrentBrightness"); break; //only work on the first object } moc.Dispose(); mos.Dispose(); return((int)curBrightness); }
public static List<PropertyData> GetPartialStuffInfo(string stuff, string[] targets) { List<PropertyData> hd = new List<PropertyData>(); try { StringBuilder sb = new StringBuilder(" SELECT "); foreach (string t in targets) { sb.Append(t).Append(" "); } sb.Append(" FROM ").Append(stuff); ManagementObjectSearcher searcher = new ManagementObjectSearcher(sb.ToString()); ManagementObjectCollection information = searcher.Get(); foreach (ManagementObject obj in information) { // Retrieving the properties (columns) // Writing column name then its value foreach (PropertyData data in obj.Properties) { Console.WriteLine("{0} = {1}", data.Name, data.Value); hd.Add(data); } } searcher.Dispose(); } catch (Exception e) { return null; } return hd; }
/// <summary> /// Query the brightness setting of the display. /// </summary> internal static int GetBrightnessLevel() { try { var s = new ManagementScope("root\\WMI"); var q = new SelectQuery("WmiMonitorBrightness"); var mos = new ManagementObjectSearcher(s, q); var moc = mos.Get(); foreach (var managementBaseObject in moc) { foreach (var o in managementBaseObject.Properties) { if (o.Name == "CurrentBrightness") return Convert.ToInt32(o.Value); } } moc.Dispose(); mos.Dispose(); } catch (ManagementException ex) { // ignore // it is possible that laptop lid is closed, and using external monitor } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return 0; }
public static List<EntHotfixes> GetHotfixDetails(ManagementScope scope) { _logger.Info("Collecting hotfix for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntHotfixes> lstHotfix = new List<EntHotfixes>(); try { query = new ObjectQuery("Select * from Win32_QuickFixEngineering"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstHotfix.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstHotfix.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is hotfix collection " + e.Message); } finally { searcher.Dispose(); } return lstHotfix; }
static void stopidle() { //taken from idlemaster project by jshackles. try { var username = WindowsIdentity.GetCurrent().Name; foreach (var process in Process.GetProcessesByName("steam-idle")) { var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ProcessID = " + process.Id); var processList = searcher.Get(); foreach (ManagementObject obj in processList) { var argList = new string[] { string.Empty, string.Empty }; var returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { if (argList[1] + "\\" + argList[0] == username) { process.Kill(); } } } searcher.Dispose(); } } catch (Exception) { MessageBox.Show("Error while stopping idle, please shut down all steam-idle.exe processes by hand from task manager."); } }
public static List<EntMultimedia> GetMultimediaDetails(ManagementScope scope) { _logger.Info("Collecting monitor details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntMultimedia> lstMultimedia = new List<EntMultimedia>(); try { query = new ObjectQuery("Select * from Win32_SoundDevice"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstMultimedia.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstMultimedia.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is multimedia collection " + e.Message); } finally { searcher.Dispose(); } return lstMultimedia; }
public static List<EntUserGroups>GetUserGroupDetails(ManagementScope scope) { _scope = scope; _logger.Info("Collecting user groups details for machine " + _scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntUserGroups> lstUserGroup = new List<EntUserGroups>(); try { query = new ObjectQuery("Select * from Win32_Group"); searcher = new ManagementObjectSearcher(_scope, query); objects = searcher.Get(); lstUserGroup.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstUserGroup.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in user groups collection " + e.Message); } finally { searcher.Dispose(); _scope = null; } return lstUserGroup; }
void refreshProcess() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process"); foreach (ManagementObject manObj in searcher.Get()) { if (!IsExistInfoUnit(array, Convert.ToInt32(manObj["ProcessID"]))) { ProcessInfoUnit unitInfo = new ProcessInfoUnit(); unitInfo.ProcessID = int.Parse(manObj["ProcessID"].ToString()); if (manObj["Caption"] != null) unitInfo.Caption = manObj["Caption"].ToString(); if (manObj["CommandLine"] != null) unitInfo.CommandLine = manObj["CommandLine"].ToString(); if (manObj["CreationDate"] != null) { string date = manObj["CreationDate"].ToString(); date = date.Substring(0, 4) + "-" + date.Substring(4, 2) + "-" + date.Substring(6, 2) + " " + date.Substring(8, 2) + ":" + date.Substring(10, 2) + ":" + date.Substring(12, 2); unitInfo.CreationDate = DateTime.Parse(date); } array.Add(unitInfo); } } searcher.Dispose(); }
public static List<EntOS> GetOSDetails(ManagementScope scope) { _logger.Info("Collecting OS details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntOS> lstOS = new List<EntOS>(); try { query = new ObjectQuery("Select * from Win32_OperatingSystem"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstOS.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstOS.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in OS collection " + e.Message); } finally { searcher.Dispose(); } return lstOS; }
public static List<EntDisk>GetDiskDetails(ManagementScope scope) { _logger.Info("Collecting disk details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntDisk> lstDisk = new List<EntDisk>(); try { query = new ObjectQuery("Select * from Win32_DiskDrive"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstDisk.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstDisk.Add(FillDetails(obj)); obj.Dispose(); } } catch (Exception e) { _logger.Error("Exception is disk collection " + e.Message); } finally { searcher.Dispose(); } return lstDisk; }
public static List<EntStartUp>GetStartUpDetails(ManagementScope scope) { _logger.Info("Collecting startup details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntStartUp> lstStartUp = new List<EntStartUp>(); try { query = new ObjectQuery("select * from Win32_StartupCommand where User != '.DEFAULT' and User != 'NT AUTHORITY\\\\SYSTEM'"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstStartUp.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstStartUp.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in startup collection " + e.Message); } finally { searcher.Dispose(); } return lstStartUp; }
public static List<EntEnvironmentVars>GetEnvironmentVarDetails(ManagementScope scope) { _logger.Info("Collecting Environment variable for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntEnvironmentVars> lstEnvVars = new List<EntEnvironmentVars>(); try { query = new ObjectQuery("Select * from Win32_Environment"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstEnvVars.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstEnvVars.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is Environment var collection " + e.Message); } finally { searcher.Dispose(); } return lstEnvVars; }
/* /// <summary> /// /// </summary> internal static void AdapterConfiguration() { // http://msdn.microsoft.com/en-us/library/aa394217(v=VS.85).aspx } */ /// <summary> /// /// </summary> internal static void EnableAdapters() { Log.AppendHeader( logfile, "Network Configuration" ); ManagementObjectSearcher searcher = null; try { searcher = new ManagementObjectSearcher( "Select * from Win32_NetworkAdapter" ); foreach ( ManagementObject mo in searcher.Get() ) { try { // Works for Vista and later // http://msdn.microsoft.com/en-us/library/aa390385(v=VS.85).aspx UInt32 success = (UInt32)mo.InvokeMethod( "Enable", null ); if ( success == 0 ) Display.UpdateStatus( mo["Caption"].ToString() + " enabled" ); } catch ( Exception ) { } finally { } } } catch ( Exception ) { } finally { // Cleanup if ( searcher != null ) { searcher.Dispose(); searcher = null; } } }
private void button1_Click(object sender, EventArgs e) { //PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { byte[] curBytes = o.Properties["IOBytes"].Value as byte[]; curBytes[81] = 100; o.SetPropertyValue("IOBytes", curBytes); //properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }
public static string GetCpuCore() { ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection cpus = mc.GetInstances(); string count = null; string co = null; ManagementObjectSearcher mySearch = new ManagementObjectSearcher("select * from Win32_Processor"); foreach (ManagementObject mo in mySearch.Get()) { count = mo.Properties["NumberOfCores"].Value.ToString(); } mc.Dispose(); mySearch.Dispose(); return count; }
private void WMIForm_Load(object sender, EventArgs e) { SelectQuery sq = new SelectQuery("Win32_OperatingSystem"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); ManagementObjectCollection moc = mos.Get(); foreach (ManagementObject mo in moc) { foreach (PropertyData pd in mo.Properties) { richTextBox1.AppendText(pd.Name + ":" + pd.Value + "\n"); } } moc.Dispose(); mos.Dispose(); sq = null; }
static void injectBrightnessWithValue(byte brightness) { System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { ManObject.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, brightness }); break; } ManObjC.Dispose(); ManObjS.Dispose(); }
// Set screen brightness static void SetBrightness(byte targetBrightness) { System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); // Define scope (namespace) System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); // Define query System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); // Output current screen brightness System.Management.ManagementObjectCollection moc = mos.Get(); // Store result is reversed order - apparently won't work otherwise foreach (System.Management.ManagementObject o in moc) { o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); break; // Only work on the first object } moc.Dispose(); mos.Dispose(); }
public static ArgumentTokenCollection Lookup(int processId) { string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE ProcessId = {0}", processId); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery); ManagementObjectCollection retObjectCollection = searcher.Get(); try { string commandLine = string.Empty; if (retObjectCollection.Count == 0 || retObjectCollection.Count > 1) { return ArgumentTokenCollection.Empty; } using (var enumerator = retObjectCollection.GetEnumerator()) { if (enumerator.MoveNext()) { commandLine = enumerator.Current["CommandLine"].ToString(); } } var parser = new ArgumentParser(commandLine); return parser.GetArguments(); } finally { if (searcher != null) { searcher.Dispose(); } if (retObjectCollection != null) { retObjectCollection.Dispose(); } } //foreach (ManagementObject retObject in retObjectCollection) //{ // return retObject["CommandLine"].ToString(); //} }
private void button1_Click(object sender, EventArgs e) { this.UseWaitCursor = true; buttonSave.Enabled = false; checkedListBoxPrinters.Enabled = false; listBoxPrinters.Enabled = false; labelWait.Left = splitContainer1.Left + (splitContainer1.Width - labelWait.Width) / 2; labelWait.Top = splitContainer1.Top + (splitContainer1.Panel1.Height - labelWait.Height) / 2; labelWait.Visible = true; checkedListBoxPrinters.Refresh(); listBoxPrinters.Refresh(); labelWait.Refresh(); this.Refresh(); PrintServer ps = new PrintServer(); foreach (object o in checkedListBoxPrinters.Items) { string proc = ""; int i = checkedListBoxPrinters.Items.IndexOf(o); if (checkedListBoxPrinters.GetItemChecked(i)) { proc = "mariaprint"; } else { proc = "winprint"; } System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Printer where Name='" + o.ToString() + "'"); System.Management.ManagementObjectCollection moc = mos.Get(); foreach (System.Management.ManagementObject printer in moc) { printer["PrintProcessor"] = proc; printer.Put(); printer.Dispose(); } moc.Dispose(); mos.Dispose(); } this.UseWaitCursor = false; this.Close(); }
public void InitPrintForm() { //取得Printer集合 ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_Printer"); ManagementObjectCollection moc = mos.Get(); foreach (ManagementObject mo in moc) { //名字取得 cmbPrinters.Items.Add(mo["Name"].ToString()); // if ((((uint)mo["Attributes"]) & 4) == 4) { //默认选项 cmbPrinters.SelectedIndex = cmbPrinters.Items.Count - 1; } } mos.Dispose(); }
static int FetchCurrentBrightness() { byte CurrentBrightness = 0; System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightness"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { CurrentBrightness = (byte)ManObject.GetPropertyValue("CurrentBrightness"); break; } ManObjC.Dispose(); ManObjS.Dispose(); return((int)CurrentBrightness); }
private bool setBrightness(int brightness) { byte brightnessInBytes; if (brightness >= 0 && brightness <= 100) { brightnessInBytes = (byte)(brightness); } else { return(false); } try { /* DANGER ZONE CODE - Only about 80% sure what this does */ System.Management.ManagementScope scope = new System.Management.ManagementScope("root\\WMI"); System.Management.SelectQuery query = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(scope, query); System.Management.ManagementObjectCollection moc = mos.Get(); foreach (System.Management.ManagementObject o in moc) //Don't ask questions you don't want to know the answer to { o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, brightnessInBytes }); break; //Searously } moc.Dispose(); mos.Dispose(); /* END OF DANGER ZONE CODE */ } catch (Exception E) { Console.WriteLine(E.ToString()); return(false); } return(true); }
// Function queries the system using WMI and returns the serial port number if the device // is connected to the system, -1 otherwise. public short DeviceUpdatedSerialPort() { this.serialModel.SetSerialPortNumber(-1); // Getting a list of all available com port devices and their friendly names // must add System.Management DLL resource to solution before using this // Project -> Add Reference -> .Net tab, choose System.Management ManagementObjectSearcher searcher = new ManagementObjectSearcher( "root\\CIMV2", "Select Name from Win32_PnpEntity where ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\""); int length = searcher.Get().Count; if (length > 0) { ManagementObject[] deviceArray = new ManagementObject[searcher.Get().Count]; searcher.Get().CopyTo(deviceArray, 0); bool found = false; for (int index = 0; !found && index < deviceArray.Length; index++) { string name = deviceArray[index].GetPropertyValue("Name").ToString(); // Checks if the current device is the desired. if (name.Contains(SerialModel.DeviceName)) { found = true; short startIndex = (short)(name.LastIndexOf("M") + 1); short endIndex = (short)name.LastIndexOf(")"); // The maximum number of COM and LPT ports that Windows NT supports is 256 this.serialModel.SetSerialPortNumber( Convert.ToInt16(name.Substring(startIndex, endIndex - startIndex))); } } searcher.Dispose(); } return this.serialModel.GetSerialPortNumber(); }
/// <summary> /// /// </summary> internal static string GetWMIProperty( string Class, string PropertyName ) { string result = string.Empty; // ManagementObjectSearcher searcher = new ManagementObjectSearcher( "SELECT " + PropertyName + " FROM " + Class ); // foreach ( ManagementObject mo in searcher.Get() ) { result = mo[PropertyName].ToString(); break; } // Cleanup if ( searcher != null ) { searcher.Dispose(); searcher = null; } // return result.Trim(); }
public override void Execute(object context = null) { ActionsHomeModel pc = context as ActionsHomeModel; //Can only be processed if the machine is online... if (pc.Status == ComputerStates.Online || pc.Status == ComputerStates.LoggedOn) { ManagementScope oMs = ConnectToClient(pc.Name); string sDCMScheduleID = null; if (oMs != null && string.IsNullOrEmpty(sDCMScheduleID)) { ManagementScope oMs2 = new ManagementScope(string.Format("\\\\{0}\\ROOT\\ccm\\policy\\machine\\actualconfig", pc.Name)); ManagementObjectCollection moc = new ManagementObjectSearcher(oMs2, new ObjectQuery("Select * from CCM_Scheduler_ScheduledMessage WHERE TargetEndPoint = 'direct:DCMAgent'")).Get(); foreach (ManagementObject mo in moc) { try { string sID = mo["ScheduledMessageID"].ToString(); if (!string.IsNullOrEmpty(sID)) { sDCMScheduleID = sID; if (string.IsNullOrEmpty(sDCMScheduleID)) { //throw new System.Exception("Not Found!"); } else { if (RunScheduleID(sDCMScheduleID, oMs)) { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Completed; }), null); } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Error; }), null); } } } } catch { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Error; }), null); } finally { mo.Dispose(); moc.Dispose(); GC.Collect(); } } } } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Pending; }), null); } }
/// <summary> /// Gets sound information /// </summary> void GetSoundInfo() { SelectQuery query = new SelectQuery("Win32_SoundDevice"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); int count = 0; foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { try { mvarSndController.Add(info["Name"].ToString()); } catch { mvarSndController.Add(MUnknown); } try { mvarSndManufacturer.Add(info["Manufacturer"].ToString()); } catch { mvarSndManufacturer.Add(MUnknown); } try { mvarSndDMABufferSize.Add(info["DMABufferSize"].ToString()); } catch { mvarSndDMABufferSize.Add(MUnknown); } count++; mvarSndNumberOfControllers = count; } catch { mvarSndNumberOfControllers = 0; mvarSndController.Add(""); mvarSndDMABufferSize.Add(""); mvarSndManufacturer.Add(""); } } if (search != null) { search.Dispose(); } }
/// <summary> /// Gets video information /// </summary> void GetVideoInfo() { SelectQuery query = new SelectQuery("Win32_VideoController"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); int count = 0; foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { try { mvarVidController.Add(info["Name"].ToString()); } catch { mvarVidController.Add(MUnknown); } try { if (Convert.ToInt32(info["AdapterRAM"]) == 0) { mvarVidRam.Add(MUnknown); } else { mvarVidRam.Add(FormatBytes(Convert.ToDouble(info["AdapterRAM"]))); } } catch { mvarVidRam.Add(MUnknown); } try { if (Convert.ToUInt32(info["CurrentRefreshRate"]) == 0) { mvarVidRefreshRate.Add("Default"); } else if (Convert.ToUInt32(info["CurrentRefreshRate"]) == 0xFFFFFFFF) { mvarVidRefreshRate.Add("Optimal"); } else { mvarVidRefreshRate.Add(info["CurrentRefreshRate"] + " Hz"); } } catch { mvarVidRefreshRate.Add(MUnknown); } try { mvarVidScreenColors.Add(ReturnColors(Convert.ToInt32(info["CurrentBitsPerPixel"]))); } catch { mvarVidScreenColors.Add(MUnknown); } count++; mvarVidNumberOfControllers = count; } catch { mvarVidNumberOfControllers = 0; } } if (search != null) { search.Dispose(); } }
/// <summary> /// Gets service information /// </summary> void GetServiceInfo() { SelectQuery query = new SelectQuery("Win32_Service"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach (ManagementObject sinfo in search.Get()) { try { mvarServiceDisplayName.Add(sinfo["DisplayName"].ToString()); } catch { mvarServiceDisplayName.Add(MUnknown); } try { mvarServiceDescription.Add(sinfo["Description"].ToString()); } catch { mvarServiceDescription.Add(MUnknown); } try { mvarServiceStartMode.Add(sinfo["StartMode"].ToString()); } catch { mvarServiceStartMode.Add(MUnknown); } try { mvarServiceState.Add(sinfo["State"].ToString()); } catch { mvarServiceState.Add(MUnknown); } try { mvarServiceStatus.Add(sinfo["Status"].ToString()); } catch { mvarServiceStatus.Add(MUnknown); } try { mvarServicePathName.Add(sinfo["PathName"].ToString()); } catch { mvarServicePathName.Add(MUnknown); } } if (search != null) { search.Dispose(); } }
/// <summary> /// Checks if there is a part of domain /// </summary> /// <returns>true - if yes, false - otherwise</returns> bool GetOSPartOfDomain() { bool temp = false; SelectQuery query = new SelectQuery("Win32_ComputerSystem"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach (ManagementObject tempLoopVar_info in search.Get()) { try { temp = Convert.ToBoolean(info["PartOfDomain"]); } catch { temp = false; } } if (search != null) { search.Dispose(); } return temp; }
/// <summary> /// Gets OS full name /// </summary> /// <returns></returns> string GetOSFullName() { string temp = ""; SelectQuery query = new SelectQuery("Win32_OperatingSystem"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { temp = Convert.ToString(info["Caption"]); } catch { temp = ""; } } if (search != null) { search.Dispose(); } return temp; }
private void SetSlideBarStatus(int a, int b) { if (a != 1) { return; } PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); while (true) { mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { byte[] curBytes = o.Properties["IOBytes"].Value as byte[]; if (b == 32 || b == 33) { curBytes[84] = (byte)(b % 2); } if (b == 0 || b == 1) { curBytes[83] = (byte)(b % 2); } //curBytes[85] = 1; //curBytes[66] = 4; o.SetPropertyValue("IOBytes", curBytes); //properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } //Console.WriteLine(properties["IOBytes"].Value); PropertyData ioBytes = properties["IOBytes"]; byte[] bytes = ioBytes.Value as byte[]; //bytes[83] = 100; //lastBytes = bytes; //((byte[])ioBytes.Value)[83] = 4; //((byte[])ioBytes.Value)[84] = 100; //int place = -1; //if (!isTheSame(bytes, out place)) //{ // Console.WriteLine("PLACE: " + place); // Console.WriteLine(BitConverter.ToString(bytes)); //} //if (bytes[83] < 3) break; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }
public static ManagementObjectCollection QueryLocalWMICollection(string scope, string query) { ManagementScope ms = null; int numTrial = 0; bool connected = false; do { try { if (scope == null) ms = new ManagementScope(@"\\.\root\cimv2", new ConnectionOptions()); else ms = new ManagementScope(scope, new ConnectionOptions()); ms.Connect(); connected = true; } catch (Exception) // in the booting period, the WMI service may not be ready; { EucaLogger.Warning("WMI service is not responding; will retry"); System.Threading.Thread.Sleep(PAUSE_SEC_BETWEEN_RETRY * 1000); continue; } } while (numTrial++ < RETRY); if (!connected || ms == null || !ms.IsConnected) throw new EucaException("Cannot establish connection to the management provider"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, new ObjectQuery(query)); ManagementObjectCollection result = searcher.Get(); searcher.Dispose(); return result; }
void GetNetInterfaceInfo() { var query = new SelectQuery("Win32_NetworkAdapterConfiguration"); var search = new ManagementObjectSearcher(query); int count = 0; string[] temp = null; foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { mvarNetDefaultTtl.Add(info["DefaultTTL"].ToString()); } catch { mvarNetDefaultTtl.Add("N/A"); } try { mvarNetDhcpEnabled.Add(Convert.ToBoolean(info["DHCPEnabled"])); } catch { mvarNetDhcpEnabled.Add(false); } try { mvarNetDhcpLeaseExpires.Add(info["DHCPLeaseExpires"].ToString().Substring( 0, 8).Insert(4, "-").Insert(7, "-")); } catch { mvarNetDhcpLeaseExpires.Add("N/A"); } try { mvarNetDhcpLeaseObtained.Add(info["DHCPLeaseObtained"].ToString().Substring( 0, 8).Insert(4, "-").Insert(7, "-")); } catch { mvarNetDhcpLeaseObtained.Add("N/A"); } try { mvarNetDhcpServer.Add(info["DHCPServer"].ToString()); } catch { mvarNetDhcpServer.Add("N/A"); } try { mvarNetHostName.Add(info["DNSHostName"].ToString()); } catch { mvarNetHostName.Add("N/A"); } try { mvarNetDomain.Add(info["DNSDomain"].ToString()); } catch { mvarNetDomain.Add("N/A"); } try { mvarNetIPEnabled.Add(Convert.ToBoolean(info["IPEnabled"])); } catch { mvarNetIPEnabled.Add(false); } try { temp = (string[])info["IPAddress"]; mvarNetIPAddress.Add(temp[0]); } catch { mvarNetIPAddress.Add("N/A"); } try { mvarNetMtu.Add(FormatBytes(Convert.ToDouble(info["MTU"]))); } catch { mvarNetMtu.Add("N/A"); } try { mvarNetTcpNumConnections.Add(info["TCPNumConnections"].ToString()); } catch { mvarNetTcpNumConnections.Add("N/A"); } try { mvarNetTcpWindowSize.Add(FormatBytes(Convert.ToDouble(info["TcpWindowSize"]))); } catch { mvarNetTcpWindowSize.Add("N/A"); } count++; } if (search != null) { search.Dispose(); } }
/// <summary> /// Gets OS Bootup state /// </summary> /// <returns>string containing the state</returns> string GetOSBootupState() { string temp = string.Empty; SelectQuery query = new SelectQuery("Win32_ComputerSystem"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { temp = Convert.ToString(info["BootupState"]); } catch { temp = ""; } } if (search != null) { search.Dispose(); } return temp; }
/// <summary> /// 测IP延迟 /// </summary> public void SetSpeed() { Stopwatch span = new Stopwatch(); ManagementObjectSearcher mos = null; ManagementObjectCollection moc = null; try { string searchString = string.Format("select * from win32_PingStatus where Address = '{0}'", this.Ip); mos = new ManagementObjectSearcher(searchString); moc = mos.Get(); foreach (ManagementObject mo in moc) { object obj = mo.Properties["StatusCode"].Value; object str = mo.Properties["ResponseTime"].Value; if (obj == null) { lock (thisobject) { this.IsNotValid = true; this.Message = "PING 执行失败。可能是主机未知。"; } } else { if (obj.ToString().Trim() == "0") { this.Message = "可用"; this.Speed = new TimeSpan?(new TimeSpan(Convert.ToInt64(str))); break; } lock (thisobject) { this.IsForbidden = true; this.Message = "PING 不通!"; } } } } catch (Exception ex) { this.Message = ex.Message; } finally { if (moc != null) moc.Dispose(); if (mos != null) mos.Dispose(); } }
/// <summary> /// Gets OS domain name /// </summary> /// <returns></returns> string GetOSDomain() { string temp = ""; var query = new SelectQuery("Win32_ComputerSystem"); var search = new ManagementObjectSearcher(query); foreach (ManagementObject tempLoopVar_info in search.Get()) { info = tempLoopVar_info; try { temp = Convert.ToString(info["Domain"]); } catch { temp = ""; } } if (search != null) { search.Dispose(); } return temp; }
public static string[] GetCpuMhz() { ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection cpus = mc.GetInstances(); string[] mHz = new string[cpus.Count]; int c = 0; ManagementObjectSearcher mySearch = new ManagementObjectSearcher("select * from Win32_Processor"); foreach (ManagementObject mo in mySearch.Get()) { mHz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString(); c++; } mc.Dispose(); mySearch.Dispose(); return mHz; }
static void Main(string[] args) { Console.SetWindowSize(Console.LargestWindowWidth - 5, Console.LargestWindowHeight - 1); PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; int repeatTimes = 0; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); while (true) { using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = mox.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; ConsoleKeyInfo ckey = Console.ReadKey(); if (ckey.Key == ConsoleKey.C) { break; } if (ckey.Key == ConsoleKey.F) { managementObject.SetPropertyValue("Active", false); } else { if (ckey.Key == ConsoleKey.T) { managementObject.SetPropertyValue("Active", true); } else { Console.WriteLine((bool)managementObject["Active"]); } } managementObject.Put(); } } } while (true) { System.Threading.Thread.Sleep(200); mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } //Console.WriteLine(properties["IOBytes"].Value); PropertyData ioBytes = properties["IOBytes"]; byte[] bytes = ioBytes.Value as byte[]; //bytes[83] = 100; //lastBytes = bytes; //((byte[])ioBytes.Value)[83] = 4; //((byte[])ioBytes.Value)[84] = 100; int place = -1; if (!isTheSame(bytes, out place)) { if (++repeatTimes >= 10) { repeatTimes = 0; Console.Clear(); } string message = "PLACE: " + place + "\r\n" + BitConverter.ToString(bytes); Console.WriteLine(message); } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }