protected virtual void GetOperatingSystemInfo(string Name, string UserName, string Password) { if (string.IsNullOrEmpty(Name)) throw new ArgumentNullException("Name"); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempNetworkAdapter in Collection) { if (TempNetworkAdapter.Properties["LastBootUpTime"].Value != null) { LastBootUpTime = ManagementDateTimeConverter.ToDateTime(TempNetworkAdapter.Properties["LastBootUpTime"].Value.ToString()); } } } } }
public static string GetDeviceId(string driveLetter) { string deviceId = ""; try { Thread thread = new Thread(() => { var index = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition").Get().Cast<ManagementObject>(); var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive").Get().Cast<ManagementObject>(); var drive = (from i in index where i["Dependent"].ToString().Contains(driveLetter) select i).FirstOrDefault(); var key = drive["Antecedent"].ToString().Split('#')[1].Split(',')[0]; var disk = (from d in disks where d["Name"].ToString() == "\\\\.\\PHYSICALDRIVE" + key select d).FirstOrDefault(); deviceId = disk["PNPDeviceID"].ToString().Split('\\').Last(); }); thread.Start(); thread.Join(); } catch (Exception ex) { MessageBox.Show(ex.Message); } return deviceId; }
/// <summary> /// Get the child processes for a given process /// </summary> /// <param name="process"></param> /// <returns></returns> public static List<Process> GetChildProcesses(this Process process) { var results = new List<Process>(); // query the management system objects for any process that has the current // process listed as it's parentprocessid string queryText = string.Format("select processid from win32_process where parentprocessid = {0}", process.Id); using (var searcher = new ManagementObjectSearcher(queryText)) { foreach (var obj in searcher.Get()) { object data = obj.Properties["processid"].Value; if (data != null) { // retrieve the process var childId = Convert.ToInt32(data); var childProcess = Process.GetProcessById(childId); // ensure the current process is still live if (childProcess != null) results.Add(childProcess); } } } return results; }
/// <summary> /// 获取系统内存大小 /// </summary> /// <returns> 内存大小(单位M) </returns> private static int GetPhisicalMemory() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象 searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new[] {"Capacity"}); //设置查询条件 ManagementObjectCollection collection = searcher.Get(); //获取内存容量 ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); long capacity = 0; while (em.MoveNext()) { ManagementBaseObject baseObj = em.Current; if (baseObj.Properties["Capacity"].Value != null) { try { capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString()); } catch { return 0; } } } return (int) (capacity/1024/1024); }
public BitcoinQProcess(Process process) { this._Process = process; WqlObjectQuery wqlQuery = new WqlObjectQuery("Select * from Win32_Process where Handle=\"" + process.Id + "\""); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery); var result = searcher.Get().OfType<ManagementObject>().FirstOrDefault(); if(result != null) { _CommandLine = result["CommandLine"].ToString(); var configurationFile = GetConfigurationFile(); if(configurationFile != null && File.Exists(configurationFile)) { _Configuration = File.ReadAllText(configurationFile); _Configuration = Regex.Replace(_Configuration, "(#.*)", ""); ParseConfigurationFile(); } ParseCommandLine(); FillWithDefault(); } }
/// <summary> /// Initializes the <see cref="PlatformHelper"/> class. /// </summary> static PlatformHelper() { Win32NT = Environment.OSVersion.Platform == PlatformID.Win32NT; XpOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 5; VistaOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 6; SevenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 1)); EightOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 2, 9200)); EightPointOneOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 3)); TenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(10, 0)); RunningOnMono = Type.GetType("Mono.Runtime") != null; Name = "Unknown OS"; using ( ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")) { foreach (ManagementObject os in searcher.Get()) { Name = os["Caption"].ToString(); break; } } Name = Regex.Replace(Name, "^.*(?=Windows)", "").TrimEnd().TrimStart(); // Remove everything before first match "Windows" and trim end & start Is64Bit = Environment.Is64BitOperatingSystem; FullName = string.Format("{0} {1} Bit", Name, Is64Bit ? 64 : 32); }
public static string GetNiceName(string port) { if (serialportproblem) return ""; DateTime start = DateTime.Now; try { ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == port.ToUpper()) { DateTime end = DateTime.Now; if ((end - start).TotalSeconds > 5) serialportproblem = true; return obj2.Properties["Name"].Value.ToString(); } } } catch { } return ""; }
public string GetProcessUserName(int pid) { string text1 = null; SelectQuery query = new SelectQuery("Select * from Win32_Process WHERE processID=" + pid); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); try { foreach (ManagementObject disk in searcher.Get()) { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; inPar = disk.GetMethodParameters("GetOwner"); outPar = disk.InvokeMethod("GetOwner", inPar, null); text1 = outPar["User"].ToString(); break; } } catch { text1 = "SYSTEM"; } return text1; }
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 virtual object DoCheck() { var processStats = ProcessStats(); var results = new ArrayList(); using (var query = new ManagementObjectSearcher("SELECT * FROM Win32_Process")) { foreach (ManagementObject process in query.Get()) { try { var processId = (uint)process.GetPropertyValue("ProcessId"); var imageName = (string)process.GetPropertyValue("Name"); // Ignore System Idle Process for now if (imageName.ToString().ToLower() == "system idle process") { continue; } var fullUserName = string.Empty; var outParameters = process.InvokeMethod("GetOwner", null, null); if (outParameters["User"] != null) { fullUserName = string.Format(@"{0}\{1}", outParameters["Domain"], outParameters["User"]); } var stats = processStats[processId]; var cpuPercentage = stats[0]; ulong workingSet = stats[1]; decimal memoryPercentage = Decimal.Round(((decimal)workingSet / (decimal)_totalMemory * 100), 2); results.Add(new object[] { processId, imageName, fullUserName, cpuPercentage, memoryPercentage, workingSet }); // flag check if (Agent.Flags.ContainsKey("ProcessCheck")) { if (imageName == Agent.Flags["ProcessCheck"]) { bool perf = PerformanceCounterBasedProcessCheck.IsProcessRunning(imageName); if (!perf) { Log.Error("Process Check: '" + Agent.Flags["ProcessCheck"] + "' process does not show in Perf Counters."); } } } } catch (ManagementException ex) { // Process could have ended before reaching this point in the loop if (ex.Message.ToLower() == "not found") { continue; } } } return results; } }
public void GetInformationTest() { var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData"); var thresSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictThresholds"); var searcherEnumerator = searcher.Get().GetEnumerator(); var thresSearcherEnumerator = thresSearcher.Get().GetEnumerator(); while (searcherEnumerator.MoveNext() && thresSearcherEnumerator.MoveNext()) { byte[] arrVendorSpecific = (byte[])searcherEnumerator.Current.GetPropertyValue("VendorSpecific"); byte[] arrThreshold = (byte[])thresSearcherEnumerator.Current.GetPropertyValue("VendorSpecific"); Console.WriteLine("-----------------------------------"); Console.WriteLine("MSStorageDriver_ATAPISmartData instance"); Console.WriteLine("-----------------------------------"); // Create SMART data from 'vendor specific' array var d = new SmartData(arrVendorSpecific, arrThreshold); foreach (var b in d.Attributes) { Console.Write("{0} : {1} : {2} : ", b.AttributeType, b.Value, b.Threshold); string rawData = BitConverter.ToString(b.VendorData.Reverse().ToArray()).Replace("-", string.Empty); Console.Write("{0}, {1}", rawData, int.Parse(rawData, NumberStyles.HexNumber)); Console.WriteLine(); } } searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictStatus"); foreach (ManagementObject queryObj in searcher.Get()) { var arrVendorSpecific = (bool) queryObj.GetPropertyValue("PredictFailure"); Console.Write("IsOK: {0}", !arrVendorSpecific); } }
public static void Do(string strToFindInCommandLine, string strToFindInCommandLine2, IList<string> filename, bool giveFocus = true) { int procID = 0; string wmiQuery = "select ProcessId, CommandLine from Win32_Process"; ManagementObjectSearcher search = new ManagementObjectSearcher(wmiQuery); ManagementObjectCollection processList = search.Get(); foreach (ManagementObject process in processList) { if (process["CommandLine"] != null) { var cmdLine = process["CommandLine"].ToString(); if (cmdLine.Contains(strToFindInCommandLine) && cmdLine.Contains(strToFindInCommandLine2)) { procID = Convert.ToInt32(process["ProcessId"]); } } } if (procID != 0) { IntPtr winHandle = FindWindow.GetProcessWindow(procID); MmdDrop.DropFile(winHandle, filename.Select(x => new MmdDropFile(x)).ToList()); if (giveFocus) SetForegroundWindow(winHandle); } }
/// <summary> /// Gets COM port list. /// </summary> /// <returns>Enumerable list of COM ports.</returns> public static IEnumerable<ComPortItem> GetComPorts() { var result = new List<ComPortItem>(); ManagementScope connectionScope = new ManagementScope(); SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery); try { foreach (ManagementObject item in searcher.Get()) { string portName = item["DeviceID"].ToString(); string portDescription = item["DeviceID"].ToString(); // COM port with Arduino is not detected. // portDescription.Contains("Arduino") is not working. // I should find out how to get value "Arduino Uno" from "Описание устройства, предоставленное шиной" parameter. // And where is this parameter? result.Add(new ComPortItem(portName, portDescription.Contains("Arduino"))); } } catch (ManagementException) { } return result; }
internal static string GenerateComputerID() { //Creates the HWID from the ProcessorID, Video Controller RAM and the size of the disk drive ; you can change this of course StringBuilder computerID = new StringBuilder(); ManagementObjectSearcher searcher; searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["ProcessorId"]); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["AdapterRAM"]); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["Size"]); } return computerID.ToString(); }
private void IterateDevices() { Console.WriteLine("Iterating"); string model; string deviceString; ManagementObjectSearcher physicalSearch = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\" AND Size <= 17179869184"); foreach (ManagementObject physicalDrive in physicalSearch.Get()) { if (physicalDrive["MediaType"].ToString().Substring(0, 9) != "Removable") continue; if (physicalDrive["Model"] == null) model = "Unknown Device"; else model = physicalDrive["Model"].ToString(); deviceString = model + " - (" + Math.Round(((double)Convert.ToDouble(physicalDrive["Size"]) / 1048576), 2) + " MB)"; ImageDevice newDevice = new ImageDevice(deviceString); newDevice.size = (long) Convert.ToInt64(physicalDrive["Size"]); newDevice.name = physicalDrive["Name"].ToString(); newDevice.partitions = Convert.ToInt32(physicalDrive["Partitions"]); // Now see if there are any mounted volumes foreach(ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + physicalDrive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get()) foreach(ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get()) newDevice.volume = "\\\\.\\" + disk["Name"].ToString(); deviceCombo.Items.Add(newDevice); } }
private string GetBatteryPercent() { try { var scope = new ManagementScope(); SelectQuery query = new SelectQuery("Select EstimatedChargeRemaining From Win32_Battery"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) { using (ManagementObjectCollection objectCollection = searcher.Get()) { foreach (ManagementObject mObj in objectCollection) //this nugget has a lot of info see here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa394074%28v=vs.85%29.aspx { PropertyData pData = mObj.Properties["EstimatedChargeRemaining"]; var val = pData.Value; if ((ushort) val > (ushort) 100) { return "100"; } else { return val.ToString().Replace("%",""); //strip % in case it duplicates } } } } return "Unk"; } catch (Exception e) { Debug.WriteLine(e); return "Unk"; } }
/// <summary> /// List the installed printer drivers and status in Windows. /// </summary> public static void CheckPrinterStatus() { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; string sQuery = "SELECT * FROM Win32_Printer"; string sDefault = string.Empty; try { query = new ManagementObjectSearcher(sQuery); queryCollection = query.Get(); //Loop thru the returned collection of printers foreach( ManagementObject mo in queryCollection ) { sDefault = string.Empty; if ((bool)mo["Default"]) sDefault = "[DEFAULT]"; MessageBox.Show("DeviceID: " + (string)mo["DeviceID"] + "\n" + "DriverName: " + Convert.ToString(mo["DriverName"]) + "\n" + "PrinterStatus: " + Convert.ToString(mo["PrinterStatus"]) + "\n" + "PrinterState: " + Convert.ToString(mo["PrinterState"]), "Printer Driver " + sDefault, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { throw ex; } }
public static bool KillProcesses(string userDomain, string userName, string procName) { //set the WMI query to get all processes using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE Name LIKE '%" + procName + "%'")) { //loop through all results foreach (ManagementObject mngObject in searcher.Get()) { try { //this object array will contain username and user domain Object[] argObj = new Object[2]; //Get the user name and user domain of current process mngObject.InvokeMethod("GetOwner", argObj); string processUserName = (string)argObj[0]; string processUserDomain = (string)argObj[1]; //if the process user name and user domain are equal to the arguments if (processUserName == userName && processUserDomain == userDomain) { mngObject.InvokeMethod("Terminate", null); } } catch { return false; } } return true; } }
internal static async Task<string> GetFriendlyName(string portName) { string result = portName; await Task.Run(() => { try { string upper = portName.ToUpper(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == upper) { result = obj2.Properties["Name"].Value.ToString(); break; } } } } catch { } }); return result; }
private static void Win32_SharesSearcher() { SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\""); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject mo in searcher.Get()) { foreach (PropertyData prop in mo.Properties) { form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine); } //form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine); } } ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null); ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null); form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine); ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo"); form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine); foreach (PropertyData prop in inParams.Properties) { form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine); } Object access = inParams.GetPropertyValue("Access"); //Stopped development here because ShareAFolder project exists. The rest of the development is there //Maybe should copy Sahare a Folder content to here at some point }
public static string getUserName() { try { var x = ""; var connectionOptions = new ConnectionOptions(); var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions); var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem"); using (var searcher = new ManagementObjectSearcher(scope, query)) { var builder = new System.Text.StringBuilder(); builder.Append(x); foreach (var row in searcher.Get()) { builder.Append((row["UserName"].ToString() + " ")); } x = builder.ToString(); return x; } } catch (Exception ex) { return ""; } }
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; }
/// <summary>Find Processes finds all processes decended from a parent process.</summary> /// <param name="identity">Identity specifies the identity of the root process...</param> /// <returns><see cref="ManagementObjectCollection"/></returns> /// <example><code> /// ManagementObjectCollection collection = ProcessFind(Process.GetCurrentProcess().Id); /// foreach (ManagementObject information in collection)</code>... /// </example> public static ManagementObjectCollection ProcessFind(int identity) { if (/*use current process?*/ identity == int.MinValue) identity = Process.GetCurrentProcess().Id; ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + identity); return searcher.Get(); }
private void find_arduino() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort"); foreach (ManagementObject queryObj in searcher.Get()) { string deviceName = queryObj["Name"].ToString(); if (deviceName.Contains("Arduino")) { _arduinoPort.PortName = queryObj["DeviceID"].ToString(); _comPortSelection.Text = queryObj["DeviceID"].ToString(); return; } } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); } }
public static String GetDefaultPrinterName() { { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); foreach (ManagementObject mo in searcher.Get()) { if (((bool?)mo["Default"]) ?? false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); return actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) return "none"; else return whole; } } return null; } }
public static String[] GetOtherPrinterNames() { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); int num = searcher.Get().Count; int count = 0; string[] otherprinters = new string[(num)]; foreach (ManagementObject mo in searcher.Get()) { if (((bool)mo["Default"]) == false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); otherprinters[count] = actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) { otherprinters[count] = null; } else { otherprinters[count] = whole; } } count = count +1; } return otherprinters; }
private string GetDriverName(string strPrinterName) { string retValue = string.Empty; //handle backslashes in network printer names if (strPrinterName.Contains("\\\\") == true) strPrinterName = strPrinterName.Replace("\\", "\\\\"); //handle apostrophes in printer names if (strPrinterName.Contains("'") == true) strPrinterName = strPrinterName.Replace("'", "\\'"); string searchQuery = string.Format("Select * FROM Win32_Printer Where Name = '{0}'", strPrinterName); ManagementObjectSearcher searchPrinters = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection printerCollection = searchPrinters.Get(); foreach (ManagementObject obj in printerCollection) { retValue = obj.Properties["DriverName"].Value.ToString(); break; } return retValue; }
private static void ApplyBIOSInformation(this DeviceHardware DeviceHardware) { try { using (var mSearcher = new ManagementObjectSearcher("SELECT SerialNumber, SMBIOSBIOSVersion FROM Win32_BIOS WHERE PrimaryBios=true")) { using (var mResults = mSearcher.Get()) { using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault()) { if (mItem != null) { var serialNumber = (string)mItem.GetPropertyValue("SerialNumber"); if (!string.IsNullOrWhiteSpace(serialNumber)) { DeviceHardware.SerialNumber = serialNumber.Trim(); } ErrorReporting.DeviceIdentifier = DeviceHardware.SerialNumber; } else { throw new Exception("No Win32_BIOS WHERE PrimaryBios=true was found"); } } } } } catch (Exception ex) { throw new Exception("Disco Client was unable to retrieve BIOS information from WMI", ex); } }
protected override void OnStart(string[] args) { // Get total memory ManagementObjectSearcher wmi = new ManagementObjectSearcher("select * from Win32_ComputerSystem"); foreach (ManagementObject o in wmi.Get()) TotalPhysicalMemory += Convert.ToSingle(o["TotalPhysicalMemory"]) / (1024 * 1024); // Would rather have these in the constructor, but instantiating them is crazy-slow and // causes net start to report a timeout CpuPerformanceCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); MemoryPerformanceCounter = new PerformanceCounter("Memory", "Available MBytes"); RequestsPerSecondCounter = new PerformanceCounter("ASP.NET Applications", "Requests/Sec", "__Total__"); // Since requests can arrive before these are first populated, fill with data so we don't // send junk to the client Status["CpuUsage"] = "0"; Status["MemoryUsage"] = "0"; Status["RequestsPerSecond"] = "0"; ClickTimer.Start(); HttpListener.Start(); // 10 worker threads for (int i = 0; i < 10; i ++) HttpListener.BeginGetContext(new AsyncCallback(RequestCallback), null); }
public static void OutputDrivesInfo() { //Disks string[] drives = Environment.GetLogicalDrives(); Console.WriteLine("**********Drives info**********"); ManagementObjectSearcher driveSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); Console.WriteLine("Physical drives info:"); foreach (ManagementObject curDrive in driveSearcher.Get()) { Console.WriteLine("\tDevice ID: {0}",curDrive["DeviceID"]); Console.WriteLine("\tInterface type: {0}", curDrive["InterfaceType"]); Console.WriteLine("\tManufacturer: {0}", curDrive["Manufacturer"]); Console.WriteLine("\tModel: {0}", curDrive["Model"]); Console.WriteLine("\tSize: {0} GB",Math.Round(System.Convert.ToDouble(curDrive["Size"]) / 1024 / 1024 / 1024, 2)); } Console.WriteLine(); Console.WriteLine("Logical drives list: " + string.Join(", ", drives)); Console.WriteLine(); Console.WriteLine("Total space on all available drives: "); for (int i = 0; i < drives.Length; i++) { DriveInfo info = new DriveInfo(drives[i]); if (info.IsReady) { Console.WriteLine("\t{0} - {1} GB ({2})", drives[i], Math.Round((double)info.TotalSize / 1024 / 1024 / 1024, 2), DriveTypeToString(info.DriveType)); } } Console.WriteLine(); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { System.Management.ManagementObjectSearcher wmiSearcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Processor"); // 使用 ManagementObjectSearcher 的 Get 方法取得所有集合 foreach (System.Management.ManagementObject obj in wmiSearcher.Get()) { // 取得CPU 序號 Current_CPUID = obj["ProcessorId"].ToString(); break; } AddSiteMapNode("檢查檔案版本", Request.Url.AbsoluteUri); CreateChoiceList(); } }
static CASLoops() { System.Management.SelectQuery query = new System.Management.SelectQuery( "SELECT NumberOfProcessors FROM Win32_ComputerSystem"); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query); System.Management.ManagementObjectCollection results = searcher.Get(); foreach (System.Management.ManagementBaseObject obj in results) { foreach (System.Management.PropertyData data in obj.Properties) { if (data.Value != null) { NCPUS = Convert.ToInt32(data.Value); } } } }
public static DataTable WMIToDataTable(string query, string computer, string username, string password) { string qry = query; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery queryObj = new System.Management.ObjectQuery(qry); if (username != string.Empty && password != string.Empty && computer != string.Empty && !computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = username; oConn.Password = password; if (!computer.StartsWith(@"\\")) { computer = @"\\" + computer; } if (!computer.ToLower().EndsWith(@"\root\cimv2")) { computer += @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, queryObj); } else { searcher = new System.Management.ManagementObjectSearcher(queryObj); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; foreach (System.Management.ManagementObject share in searcher.Get()) { if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { if (p.Type == CimType.DateTime) { values[x] = System.Management.ManagementDateTimeConverter.ToDateTime(p.Value.ToString()); } else { values[x] = p.Value; } x++; } dt.Rows.Add(values); values = null; } return(dt); }
private void getInstalledPrinters() { // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); Console.WriteLine(new String('*', 20)); listInstalledprinters.Clear(); foreach (ManagementObject mo in moc) { if ((bool)mo["Network"]) { System.Management.PropertyDataCollection pdc = mo.Properties; //Console.WriteLine(pdc["DeviceID"].Value); String printerName = (string)pdc["ShareName"].Value; String location = (string)pdc["Location"].Value; String driverName = (string)pdc["DriverName"].Value; String unc = (string)pdc["Name"].Value; listInstalledprinters.Add(unc); ListViewItem lvi = new ListViewItem(printerName); lvi.SubItems.Add(location); lvi.SubItems.Add(driverName); lvi.SubItems.Add(unc); lvi.Name = unc; // <-- key if (listViewInstalledPrinters.InvokeRequired) { listViewInstalledPrinters.Invoke(new AddListViewItemCallback(ListViewAdd), new object[] { listViewInstalledPrinters, lvi }); } else { ListViewAdd(listViewInstalledPrinters, lvi); } /* * foreach (System.Management.PropertyData pd in pdc) * { * Console.WriteLine("{0} = {1}", pd.Name, mo[pd.Name]); * } */ } } if (listViewInstalledPrinters.InvokeRequired) { listViewInstalledPrinters.Invoke(new CleanupInstalledPrintersCallback(CleanupInstalledPrinters)); } else { CleanupInstalledPrinters(); } }
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 ExecutionResult ExecuteActions(List <Action> Actions) { ExecutionResult SNDBSResult = ExecutionResult.TasksSucceeded; if (Actions.Count > 0) { string SCERoot = Environment.GetEnvironmentVariable("SCE_ROOT_DIR"); bool bSNDBSExists = false; if (SCERoot != null) { string SNDBSExecutable = Path.Combine(SCERoot, "Common/SN-DBS/bin/dbsbuild.exe"); // Check that SN-DBS is available bSNDBSExists = File.Exists(SNDBSExecutable); } if (bSNDBSExists == false) { return(ExecutionResult.Unavailable); } // Use WMI to figure out physical cores, excluding hyper threading. int NumCores = 0; if (!Utils.IsRunningOnMono) { try { using (ManagementObjectSearcher Mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor")) { ManagementObjectCollection MosCollection = Mos.Get(); foreach (ManagementBaseObject Item in MosCollection) { NumCores += int.Parse(Item["NumberOfCores"].ToString()); } } } catch (Exception Ex) { Log.TraceWarning("Unable to get the number of Cores: {0}", Ex.ToString()); Log.TraceWarning("Falling back to processor count."); } } // On some systems this requires a hot fix to work so we fall back to using the (logical) processor count. if (NumCores == 0) { NumCores = System.Environment.ProcessorCount; } // The number of actions to execute in parallel is trying to keep the CPU busy enough in presence of I/O stalls. MaxActionsToExecuteInParallel = 0; // The CPU has more logical cores than physical ones, aka uses hyper-threading. if (NumCores < System.Environment.ProcessorCount) { MaxActionsToExecuteInParallel = (int)(NumCores * BuildConfiguration.ProcessorCountMultiplier); } // No hyper-threading. Only kicking off a task per CPU to keep machine responsive. else { MaxActionsToExecuteInParallel = NumCores; } MaxActionsToExecuteInParallel = Math.Min(MaxActionsToExecuteInParallel, BuildConfiguration.MaxProcessorCount); JobNumber = 1; Dictionary <Action, ActionThread> ActionThreadDictionary = new Dictionary <Action, ActionThread>(); while (true) { bool bUnexecutedActions = false; foreach (Action Action in Actions) { ActionThread ActionThread = null; bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread); if (bFoundActionProcess == false) { bUnexecutedActions = true; ExecutionResult CompileResult = ExecuteActions(Actions, ActionThreadDictionary); if (CompileResult != ExecutionResult.TasksSucceeded) { return(ExecutionResult.TasksFailed); } break; } } if (bUnexecutedActions == false) { break; } } Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "-------- Begin Detailed Action Stats ----------------------------------------------------------"); Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "^Action Type^Duration (seconds)^Tool^Task^Using PCH"); double TotalThreadSeconds = 0; // Check whether any of the tasks failed and log action stats if wanted. foreach (KeyValuePair <Action, ActionThread> ActionProcess in ActionThreadDictionary) { Action Action = ActionProcess.Key; ActionThread ActionThread = ActionProcess.Value; // Check for pending actions, preemptive failure if (ActionThread == null) { SNDBSResult = ExecutionResult.TasksFailed; continue; } // Check for executed action but general failure if (ActionThread.ExitCode != 0) { SNDBSResult = ExecutionResult.TasksFailed; } // Log CPU time, tool and task. double ThreadSeconds = Action.Duration.TotalSeconds; Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "^{0}^{1:0.00}^{2}^{3}^{4}", Action.ActionType.ToString(), ThreadSeconds, Path.GetFileName(Action.CommandPath), Action.StatusDescription, Action.bIsUsingPCH); // Update statistics switch (Action.ActionType) { case ActionType.BuildProject: UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds; break; case ActionType.Compile: UnrealBuildTool.TotalCompileTime += ThreadSeconds; break; case ActionType.CreateAppBundle: UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds; break; case ActionType.GenerateDebugInfo: UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds; break; case ActionType.Link: UnrealBuildTool.TotalLinkTime += ThreadSeconds; break; default: UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds; break; } // Keep track of total thread seconds spent on tasks. TotalThreadSeconds += ThreadSeconds; } Log.TraceInformation("-------- End Detailed Actions Stats -----------------------------------------------------------"); // Log total CPU seconds and numbers of processors involved in tasks. Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo, LogEventType.Console, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds); } return(SNDBSResult); }
private void QueryButton_Click(object sender, System.EventArgs e) { AddToHistory(); this.StilRunning = true; this.QueryButton.Enabled = false; this.StopButton.Enabled = true; try { treeView1.Nodes.Clear(); if (this.QueryTextBox.Text != string.Empty) { string qry = QueryTextBox.Text; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery query = new System.Management.ObjectQuery(qry); if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(Computer) && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Windows.Forms.TreeNode root = new TreeNode(qry); root.Tag = "RootNode"; root.Expand(); treeView1.Nodes.Add(root); string path = ""; foreach (System.Management.ManagementObject share in searcher.Get()) { System.Windows.Forms.TreeNode item = new TreeNode(share.ClassPath.ClassName); item.Tag = "ClassNode"; root.Nodes.Add(item); path = "Enumerating:" + share.ClassPath.ClassName; foreach (System.Management.PropertyData p in share.Properties) { bool isLocal = p.IsLocal; string type = p.Type.ToString(); string origin = p.Origin; string name = p.Name; path = "Enumerating:" + share.ClassPath.ClassName + "," + name; Application.DoEvents(); bool IsArray = p.IsArray; string val = "NULL"; if (p.Value != null) { val = p.Value.ToString(); } System.Windows.Forms.TreeNode node = new TreeNode(name); node.Tag = "PropertyNode"; string display = ""; if (type.ToLower() == "string") { display = "Value='" + val + "'"; } else { display = "Value=" + val; } System.Windows.Forms.TreeNode ValueNode = new TreeNode(display); ValueNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode TypeNode = new TreeNode("Type='" + type + "'"); TypeNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode localNode = new TreeNode("IsLocal=" + isLocal); localNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode OriginNode = new TreeNode("Origin='" + origin + "'"); OriginNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode IsArrayNode = new TreeNode("IsArray=" + IsArray); IsArrayNode.Tag = "ValueNode"; node.Nodes.Add(ValueNode); node.Nodes.Add(TypeNode); node.Nodes.Add(localNode); node.Nodes.Add(OriginNode); node.Nodes.Add(IsArrayNode); if (IsArray && p.Value != null) { System.Array a = (System.Array)p.Value; for (int x = 0; x < a.Length; x++) { string v = ""; if (a.GetValue(x) != null) { v = a.GetValue(x).ToString(); } System.Windows.Forms.TreeNode arrayNode = new TreeNode(name + "[" + x + "]=" + v); arrayNode.Tag = "ArrayNode"; IsArrayNode.Nodes.Add(arrayNode); IncrementBar(); } } IncrementBar(); item.Nodes.Add(node); Application.DoEvents(); if (!this.StilRunning) { break; } } if (!this.StilRunning) { break; } } } } catch (Exception exc) { Terminals.Logging.Info("Query Button Failed", exc); MessageBox.Show("Error Thrown:" + exc.Message); } this.progressBar1.Value = 0; this.QueryButton.Enabled = true; this.StopButton.Enabled = false; }
public static void LogEnvironmentInformation() { MySandboxGame.Log.WriteLine("MyVideoModeManager.LogEnvironmentInformation - START"); MySandboxGame.Log.IncreaseIndent(); try { ManagementObjectSearcher mosComputer = new System.Management.ManagementObjectSearcher("Select Manufacturer, Model from Win32_ComputerSystem"); if (mosComputer != null) { foreach (var item in mosComputer.Get()) { MySandboxGame.Log.WriteLine("Win32_ComputerSystem.Manufacturer: " + item["Manufacturer"]); MySandboxGame.Log.WriteLine("Win32_ComputerSystem.Model: " + item["Model"]); MySandboxGame.Log.WriteLine("Virtualized: " + IsVirtualized(item["Manufacturer"].ToString(), item["Model"].ToString())); } } ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT Name FROM Win32_Processor"); if (mos != null) { foreach (ManagementObject mo in mos.Get()) { MySandboxGame.Log.WriteLine("Environment.ProcessorName: " + mo["Name"]); } } #if !XB1 // Get info about memory var memory = new WinApi.MEMORYSTATUSEX(); WinApi.GlobalMemoryStatusEx(memory); MySandboxGame.Log.WriteLine("ComputerInfo.TotalPhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalPhys) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.TotalVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalVirtual) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailablePhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailPhys) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailableVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailVirtual) + " bytes"); #else // XB1 MySandboxGame.Log.WriteLine("ComputerInfo.TotalPhysicalMemory: N/A (XB1 TODO?)"); MySandboxGame.Log.WriteLine("ComputerInfo.TotalVirtualMemory: N/A (XB1 TODO?)"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailablePhysicalMemory: N/A (XB1 TODO?)"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailableVirtualMemory: N/A (XB1 TODO?)"); #endif // XB1 // Get info about hard drives ConnectionOptions oConn = new ConnectionOptions(); ManagementScope oMs = new ManagementScope("\\\\localhost", oConn); ObjectQuery oQuery = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); using (ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery)) { ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) { string capacity = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["Size"])); string freeSpace = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["FreeSpace"])); string name = oReturn["Name"].ToString(); MySandboxGame.Log.WriteLine("Drive " + name + " | Capacity: " + capacity + " bytes | Free space: " + freeSpace + " bytes"); } oReturnCollection.Dispose(); } } catch (Exception e) { MySandboxGame.Log.WriteLine("Error occured during enumerating environment information. Application is continuing. Exception: " + e.ToString()); } MySandboxGame.Log.DecreaseIndent(); MySandboxGame.Log.WriteLine("MyVideoModeManager.LogEnvironmentInformation - END"); }
public static void SetPowerState() { //修改连接请求 Microsoft.Win32.RegistryKey registrykey; registrykey = Registry.CurrentUser; registrykey = registrykey.OpenSubKey("Software\\Microsoft\\BluetoothAuthenticationAgent", true); if (registrykey != null) { string[] keys = new string[1024]; keys = registrykey.GetValueNames(); foreach (string key in keys) { if (key.ToUpper() == "ACCEPTINCOMINGREQUESTS") { registrykey.SetValue(key, (object)0); } } } else { registrykey = Registry.CurrentUser; registrykey = registrykey.OpenSubKey("Software\\Microsoft", true); if (registrykey != null) { registrykey = registrykey.CreateSubKey("BluetoothAuthenticationAgent", RegistryKeyPermissionCheck.ReadWriteSubTree); if (registrykey != null) { registrykey.SetValue("AcceptIncomingRequests", (object)0); } } } if (GetOs() != "WIN7") { //return; } StringBuilder sbDevHst = new StringBuilder(); List <string> portsList = new List <string>(); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"); foreach (System.Management.ManagementObject mgt in searcher.Get()) { try { string Devicename = mgt["Name"].ToString(); if (Devicename == "Generic Bluetooth Radio") { foreach (PropertyData property in mgt.Properties) { string Propernames = property.Name; if (Propernames.ToUpper() == "DEVICEID") { ChangePowerManage(mgt[Propernames].ToString()); } } } if (Devicename == "Generic USB Hub") { foreach (PropertyData property in mgt.Properties) { string Propernames = property.Name; if (Propernames.ToUpper() == "DEVICEID") { ChangePowerManage(mgt[Propernames].ToString()); } } } if (Devicename == "USB Root Hub") { foreach (PropertyData property in mgt.Properties) { string Propernames = property.Name; if (Propernames.ToUpper() == "DEVICEID") { ChangePowerManage(mgt[Propernames].ToString()); } } } } catch (Exception ex) { ClsToolTip.WriteLog("Common 类" + ex.Message); } } }
// Winmate Kenkun modify on 2016/03/21 >> public String GetProcessorInformation() { // ManagementObjectSearcher 類別 : 根據指定的查詢擷取管理物件的集合 // 透過查詢語法 SELECT * FROM Win32_Processor 取得所有 Win32_Processor 類別資料 // 可參考 http://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx // 其中 CPU 型號為 ProcessorName List <CPUInfoEntity> cpuInfoList = new List <CPUInfoEntity>(); ManagementObjectCollection moCollection = null; String ProcessorName = ""; // 設定通過WMI要查詢的內容 ObjectQuery selectQuery = new ObjectQuery("select * from Win32_Processor"); // WQL語句, 設定的WMI查詢內容和WMI的操作範圍, 檢索WMI對象集合 ManagementObjectSearcher managementObjectSearch = new ManagementObjectSearcher(managementScope, selectQuery); // 非同步調用WMI查詢 moCollection = managementObjectSearch.Get(); foreach (ManagementObject mObject in moCollection) { ProcessorName = (string)mObject["Name"]; Trace.WriteLine("Win32_Processor Name : " + ProcessorName); if (IsDebugMode) { ProcessorInformation += "#CPU Information#" + "\r\n"; // ProcessorInformation += "SystemName : " + mObject["SystemName"].ToString() + "\r\n"; ProcessorInformation += "Name : " + mObject["Name"].ToString() + "\r\n"; ProcessorInformation += "Manufacturer : " + mObject["Manufacturer"].ToString() + "\r\n"; // ProcessorInformation += "CreationClassName : " + mObject["CreationClassName"].ToString() + "\r\n"; // ProcessorInformation += "Caption : " + mObject["Caption"].ToString() + "\r\n"; // ProcessorInformation += "Description : " + mObject["Description"].ToString() + "\r\n"; ProcessorInformation += "ProcessorId : " + mObject["ProcessorId"].ToString() + "\r\n"; // ProcessorInformation += "DeviceID : " + mObject["DeviceID"].ToString() + "\r\n"; // ProcessorInformation += "SocketDesignation : " + mObject["SocketDesignation"].ToString() + "\r\n"; // ProcessorInformation += "Role : " + mObject["Role"].ToString() + "\r\n"; // ProcessorInformation += "Status : " + mObject["Status"].ToString() + "\r\n"; // ProcessorInformation += "SystemCreationClassName : " + mObject["SystemCreationClassName"].ToString() + "\r\n"; // ProcessorInformation += "Version : " + mObject["Version"].ToString() + "\r\n"; ProcessorInformation += "CurrentClockSpeed : " + mObject["CurrentClockSpeed"].ToString() + "\r\n"; /* * Trace.WriteLine("#CPU Information# Win32_Processor class : "); * Trace.WriteLine("SystemName : " + mObject["SystemName"].ToString()); // WE0930 * Trace.WriteLine("Name : " + mObject["Name"].ToString());// Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz * Trace.WriteLine("Manufacturer : " + mObject["Manufacturer"].ToString());// GenuineIntel * Trace.WriteLine("CreationClassName : " + mObject["CreationClassName"].ToString());// Win32_Processor * Trace.WriteLine("Caption : " + mObject["Caption"].ToString());// Intel64 Family 6 Model 60 Stepping 3 * Trace.WriteLine("Description : " + mObject["Description"].ToString());// Intel64 Family 6 Model 60 Stepping 3 * Trace.WriteLine("ProcessorId : " + mObject["ProcessorId"].ToString());// BFEBFBFF000306C3 * Trace.WriteLine("DeviceID : " + mObject["DeviceID"].ToString());// CPU0 * Trace.WriteLine("SocketDesignation : " + mObject["SocketDesignation"].ToString());// SOCKET 0 * Trace.WriteLine("Role : " + mObject["Role"].ToString());// CPU * Trace.WriteLine("Status : " + mObject["Status"].ToString());// OK * Trace.WriteLine("SystemCreationClassName : " + mObject["SystemCreationClassName"].ToString());// Win32_ComputerSystem * Trace.WriteLine("Version : " + mObject["Version"].ToString());// * Trace.WriteLine("CurrentClockSpeed : " + mObject["CurrentClockSpeed"].ToString());// 3201 */ // Not Support // ProcessorInformation += "AssetTag : " + mObject["AssetTag"].ToString() + "\r\n"; // ProcessorInformation += "ErrorDescription : " + mObject["ErrorDescription"].ToString() + "\r\n"; // ProcessorInformation += "OtherFamilyDescription : " + mObject["OtherFamilyDescription"].ToString() + "\r\n"; // ProcessorInformation += "PartNumber : " + mObject["PartNumber"].ToString() + "\r\n"; // ProcessorInformation += "PNPDeviceID : " + mObject["PNPDeviceID"].ToString() + "\r\n"; // ProcessorInformation += "SerialNumber : " + mObject["SerialNumber"].ToString() + "\r\n"; // ProcessorInformation += "Stepping : " + mObject["Stepping"].ToString() + "\r\n"; // ProcessorInformation += "UniqueId : " + mObject["UniqueId"].ToString() + "\r\n"; CPUInfoEntity cpuInfo = new CPUInfoEntity { CPUCount = moCollection.Count, CPUMaxClockSpeed = mObject["MaxClockSpeed"] == null ? string.Empty : mObject["MaxClockSpeed"].ToString(), // 獲取最大時鐘頻率 CPUExtClock = mObject["ExtClock"] == null ? string.Empty : mObject["ExtClock"].ToString(), // 獲取外部頻率 CPUCurrentVoltage = mObject["CurrentVoltage"] == null ? string.Empty : mObject["CurrentVoltage"].ToString(), // 獲取當前電壓 CPUL2CacheSize = mObject["L2CacheSize"] == null ? string.Empty : mObject["L2CacheSize"].ToString(), // 獲取二級Cache CPUDataWidth = mObject["DataWidth"] == null ? string.Empty : mObject["DataWidth"].ToString(), // 獲取DataWidth CPUAddressWidth = mObject["AddressWidth"] == null ? string.Empty : mObject["AddressWidth"].ToString(), // 獲取AddressWidth CPUNumberOfCores = mObject["NumberOfCores"] == null ? string.Empty : mObject["NumberOfCores"].ToString(), // 核心數 CPUNumberOfLogicalProcessors = mObject["NumberOfLogicalProcessors"] == null ? string.Empty : mObject["NumberOfLogicalProcessors"].ToString(), // 邏輯處理器 CPUUsedPercent = mObject["LoadPercentage"] == null ? 0 : float.Parse(mObject["LoadPercentage"].ToString()) }; cpuInfoList.Add(cpuInfo); // 加入進去 } } #region 獲取 CPU 溫度 Double CPUtprt = 0; System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(@"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature"); foreach (System.Management.ManagementObject mo in mos.Get()) { CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10; if (IsDebugMode) { Trace.WriteLine("CPU Temperature : " + CPUtprt.ToString() + " °C"); } } #endregion if (ProcessorName.ToUpper().IndexOf("INTEL") != -1) { ProcessorName = "INTEL"; } else if (ProcessorName.ToUpper().IndexOf("VIA") != -1) { ProcessorName = "VIA"; } return(ProcessorName); }
public static object GetPowerStatus() { object status = null; string keynames = ""; StringBuilder sbDevHst = new StringBuilder(); List <string> portsList = new List <string>(); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"); foreach (System.Management.ManagementObject mgt in searcher.Get()) { try { string Devicename = mgt["Name"].ToString(); if (Devicename == "Generic Bluetooth Radio") { foreach (PropertyData property in mgt.Properties) { string Propernames = property.Name; if (Propernames.ToUpper() == "DEVICEID") { keynames = mgt[Propernames].ToString(); goto FindPowerManger; } } } } catch (Exception ex) { ClsToolTip.WriteLog("Common 类" + ex.Message); } } FindPowerManger: if (/*GetOs() == "WIN7" &&*/ !string.IsNullOrEmpty(keynames)) { try { Microsoft.Win32.RegistryKey registrykey; //////////////////////////////////// registrykey = Registry.LocalMachine; registrykey = registrykey.OpenSubKey("SYSTEM\\ControlSet001\\Enum\\" + keynames + "\\Device Parameters", true); if (registrykey != null) { string[] keys = new string[1024]; keys = registrykey.GetValueNames(); foreach (string key in keys) { if (key.ToUpper() == "SELECTIVESUSPENDENABLED") { //registrykey.SetValue(key, (object)0); status = registrykey.GetValue(key); } } } //////////////////////////////////// registrykey = Registry.LocalMachine; registrykey = registrykey.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\" + keynames + "\\Device Parameters", true); if (registrykey != null) { string[] keys = new string[1024]; keys = registrykey.GetValueNames(); foreach (string key in keys) { if (key.ToUpper() == "SELECTIVESUSPENDENABLED") { //registrykey.SetValue(key, (object)0); status = registrykey.GetValue(key); } } } } catch (Exception ex) { ClsToolTip.WriteLog("更改电源设置错误:" + ex.Message); } } return(status); }
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(); } } }
public static SoundInfo[] GetCurrentSoundInfo() { SoundInfo[] soundSourceInfos = new SoundInfo[0]; try { // TODO: properly handle when headphones are used, etc. MMDeviceEnumerator DevEnum = new MMDeviceEnumerator(); MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia); List <SoundInfo> soundSourceInfoList = new List <SoundInfo>(); SoundInfo soundInfo = null; // Note the AudioSession manager did not have a method to enumerate all sessions in windows Vista; this will only work on Win7 and newer. for (int i = 0; i < device.AudioSessionManager.Sessions.Count; i++) { AudioSessionControl session = device.AudioSessionManager.Sessions[i]; soundInfo = new SoundInfo(); // if (session.State == AudioSessionState.AudioSessionStateActive) { soundInfo.Pid = (int)session.ProcessID; soundInfo.IconPath = session.IconPath; soundInfo.DisplayName = session.DisplayName; soundInfo.SessionIdentifier = session.SessionIdentifier; soundInfo.SessionInstanceIdentifier = session.SessionInstanceIdentifier; soundInfo.IsSystemSoundsSession = session.IsSystemSoundsSession; //soundSourceInfo.State = session.State; try { int pid = (int)session.ProcessID; if (pid != 0) { string procName; if (false == ProcNameDict.TryGetValue(pid, out procName)) { try { Process p = Process.GetProcessById(pid); //TO_DO: should remove processname and windowtitle from this class (but make sure that windowtitle gets updated at appropriate interval) ProcNameDict[pid] = p.ProcessName; ProcWindowTitleDict[pid] = p.MainWindowTitle; try { if (p.Modules.Count > 0) { ProcFullPathDict[pid] = p.Modules[0].FileName; } else { ProcFullPathDict[pid] = ""; } } catch (Exception ex) { // WMI code from stackoverflow string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process"; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query); foreach (ManagementObject item in searcher.Get()) { object id = item["ProcessID"]; object path = item["ExecutablePath"]; if (path != null && id.ToString() == p.Id.ToString()) { ProcFullPathDict[pid] = path.ToString(); break; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); ProcNameDict[pid] = ""; ProcWindowTitleDict[pid] = ""; ProcFullPathDict[pid] = ""; } } soundInfo.ProcessName = ProcNameDict[pid]; soundInfo.WindowTitle = ProcWindowTitleDict[pid]; if (soundInfo.WindowTitle == "") { try { Process proc = Process.GetProcessById(pid); soundInfo.WindowTitle = proc.MainWindowTitle; if (soundInfo.WindowTitle == "") { soundInfo.WindowTitle = proc.ProcessName; } } catch { } } soundInfo.ProcessFullPath = ProcFullPathDict[pid]; if ((soundInfo.ProcessFullPath == "") && (soundInfo.IsSystemSoundsSession == false)) { int x = 0; x++; } } else { soundInfo.ProcessName = ""; soundInfo.WindowTitle = "System Sounds"; soundInfo.ProcessFullPath = ""; } } catch (Exception ex) { string msg = ex.Message; } AudioMeterInformation mi = session.AudioMeterInformation; SimpleAudioVolume vol = session.SimpleAudioVolume; soundInfo.Muted = vol.Mute; soundInfo.MixerVolume = session.SimpleAudioVolume.MasterVolume; //session.SimpleAudioVolume.MasterVolume = soundSourceInfo.ChannelVolume; soundInfo.EmittedVolume = session.AudioMeterInformation.MasterPeakValue; soundSourceInfoList.Add(soundInfo); } } // Free up the memory IntPtr pointer = Marshal.GetIUnknownForObject(device); Marshal.Release(pointer); soundSourceInfos = soundSourceInfoList.ToArray(); Array.Sort(soundSourceInfos, delegate(SoundInfo info1, SoundInfo info2) { return(info1.CompareTo(info2)); }); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex); } return(soundSourceInfos); }
private void LoadServices(string Username, string Password, string Computer) { StringBuilder sb = new StringBuilder(); string qry = "select AcceptPause, AcceptStop, Caption, CheckPoint, CreationClassName, Description, DesktopInteract, DisplayName, ErrorControl, ExitCode, InstallDate, Name, PathName, ProcessId,ServiceSpecificExitCode, ServiceType, Started, StartMode, StartName, State, Status, SystemCreationClassName, SystemName, TagId, WaitHint from win32_service"; ManagementObjectSearcher searcher; ObjectQuery query = new ObjectQuery(qry); if (Username != "" && Password != "" && Computer != "" && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; if (!Computer.StartsWith(@"\\")) { Computer = @"\\" + Computer; } if (!Computer.ToLower().EndsWith(@"\root\cimv2")) { Computer = Computer + @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; list.Clear(); foreach (System.Management.ManagementObject share in searcher.Get()) { Share s = new Share(); list.Add(share); if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { if (p != null && x < length) { values[x] = p.Value; x++; } } dt.Rows.Add(values); values = null; } this.dataGridView1.DataSource = dt; }
private void LoadServices(string Username, string Password, string Computer) { System.Text.StringBuilder sb = new StringBuilder(); string qry = "select * from win32_service"; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery query = new System.Management.ObjectQuery(qry); if (Username != "" && Password != "" && Computer != "" && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; if (!Computer.StartsWith(@"\\")) { Computer = @"\\" + Computer; } if (!Computer.ToLower().EndsWith(@"\root\cimv2")) { Computer = Computer + @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; list.Clear(); foreach (System.Management.ManagementObject share in searcher.Get()) { Share s = new Share(); list.Add(share); if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { values[x] = p.Value; x++; } dt.Rows.Add(values); values = null; } this.dataGridView1.DataSource = dt; }
public static void GetLocalMessage(out IPAddress ip, out IPAddress mask, out string mac) { ip = null; mask = null; mac = null; try { //ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); //ManagementObjectCollection nics = mc.GetInstances(); System.Management.ManagementObjectSearcher query = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration"); ManagementObjectCollection queryCollection = query.Get(); string strIp = null, strMask = null, strMac = null; foreach (var o in queryCollection) { var nic = (ManagementObject)o; if (Convert.ToBoolean(nic["IPEnabled"]) == false) { continue; } if (nic["IPAddress"] == null) { continue; } var strIpAddress = nic["IPAddress"] as string[]; if (strIpAddress != null) { strIp = strIpAddress[0]; } if (nic["IPSubnet"] == null) { continue; } var strIpSubnet = nic["IPSubnet"] as string[]; if (strIpSubnet != null) { strMask = strIpSubnet[0]; } if (nic["MACAddress"] == null) { continue; } strMac = nic["MACAddress"] as string; if (strIp != null) { ip = IPAddress.Parse(strIp); } if (strMask != null) { mask = IPAddress.Parse(strMask); } mac = strMac; break; } } catch (Exception) { throw; } }