ManagementObject 参数 WMI 一些参数(Win32_Service)

本文详细介绍了 Win32_Service 类的各项属性,包括服务是否可暂停、停止、名称、状态等,帮助读者理解 Windows 服务的基本配置和管理。

class Win32_Service : Win32_BaseService
{
  boolean AcceptPause;
  boolean AcceptStop;
  string Caption;
  uint32 CheckPoint;
  string CreationClassName;
  string Description;
  boolean DesktopInteract;
  string DisplayName;
  string ErrorControl;
  uint32 ExitCode;
  datetime InstallDate;
  string Name;
  string PathName;
  uint32 ProcessId;
  uint32 ServiceSpecificExitCode;
  string ServiceType;
  boolean Started;
  string StartMode;
  string StartName;
  string State;
  string Status;
  string SystemCreationClassName;
  string SystemName;
  uint32 TagId;
  uint32 WaitHint;
};

 

 

Properties

The Win32_Service class has the following properties.

AcceptPause
Data type: boolean
Access type: Read-only

 

Service can be paused.

 

AcceptStop
Data type: boolean
Access type: Read-only

 

Service can be stopped.

 

Caption
Data type: string
Access type: Read-only

 

Short description of the object—a one-line string.

 

CheckPoint
Data type: uint32
Access type: Read-only

 

Value that the service increments periodically to report its progress during a long start, stop, pause, or continue operation. For example, the service increments this value as it completes each step of its initialization when it is starting up. The user interface program that invokes the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending.

 

CreationClassName
Data type: string
Access type: Read-only
Qualifiers: Key, MaxLen( 256)

 

Name of the first concrete class to appear in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, the property allows all instances of this class and its subclasses to be uniquely identified.

 

Description
Data type: string
Access type: Read-only

 

Description of the object.

 

DesktopInteract
Data type: boolean
Access type: Read-only

 

Service can create or communicate with windows on the desktop.

 

DisplayName
Data type: string
Access type: Read-only

 

Display name of the service. This string has a maximum length of 256 characters. The name is case-preserved in the Service Control Manager. However, DisplayName comparisons are always case-insensitive. Constraint: accepts the same value as the Name property.

Example: "Atdisk"

 

ErrorControl
Data type: string
Access type: Read-only

 

Severity of the error if this service fails to start during startup. The value indicates the action taken by the startup program if failure occurs. All errors are logged by the computer system.

ValueMeaning
"Ignore"User is not notified.
"Normal"User is notified.
"Severe"System is restarted with the last-known-good configuration.
"Critical"System attempts to restart with a good configuration.
"Unknown"Severity of the error is unknown.

 

ExitCode
Data type: uint32
Access type: Read-only

 

Windows error code defining any problems encountered in starting or stopping the service. This property is set to ERROR_SERVICE_SPECIFIC_ERROR (1066) when the error is unique to the service represented by this class, and information about the error is available in the ServiceSpecificExitCode property. The service sets this value to NO_ERROR when running, and again upon normal termination.

 

InstallDate
Data type: datetime
Access type: Read-only

 

Date object is installed. This property does not need a value to indicate that the object is installed.

 

Name
Data type: string
Access type: Read-only

 

Unique identifier of the service that provides an indication of the functionality that is managed. This functionality is described in more detail in the Description property of the object.

 

PathName
Data type: string
Access type: Read-only

 

Fully-qualified path to the service binary file that implements the service.

Example: "/SystemRoot/System32/drivers/afd.sys"

 

ProcessId
Data type: uint32
Access type: Read-only

 

Process identifier of the service.

Example: 324

 

ServiceSpecificExitCode
Data type: uint32
Access type: Read-only

 

Service-specific error code for errors that occur while the service is either starting or stopping. The exit codes are defined by the service represented by this class. This value is only set when the ExitCode property value is ERROR_SERVICE_SPECIFIC_ERROR (1066).

 

ServiceType
Data type: string
Access type: Read-only

 

Type of service provided to calling processes.

Values are:

"Kernel Driver"
"File System Driver"
"Adapter"
"Recognizer Driver"
"Own Process"
"Share Process"
"Interactive Process"

 

Started
Data type: boolean
Access type: Read-only

 

Service has been started.

 

StartMode
Data type: string
Access type: Read-only

 

Start mode of the Windows base service.

ValueMeaning
"Boot"Device driver started by the operating system loader (valid only for driver services).
"System"Device driver started by the operating system initialization process. This value is valid only for driver services.
"Auto"Service to be started automatically by the service control manager during system startup.
"Manual"Service to be started by the service control manager when a process calls the StartService method.
"Disabled"Service that cannot be started.

 

StartName
Data type: string
Access type: Read-only

 

Account name under which a service runs. Depending on the service type, the account name may be in the form of DomainName/Username. The service process is logged by using one of these two forms when it runs. If the account belongs to the built-in domain, then ./Username can be specified. For kernel or system level drivers, StartName contains the driver object name (that is, /FileSystem/Rdr or /Driver/Xns) which the input and output (I/O) system uses to load the device driver. Additionally, if NULL is specified, the driver runs with a default object name created by the I/O system based on the service name.
Example: "DWDOM/Admin"

Windows XP:  You may use UPN format ( Username@DomainName) to specify the StartName.
Windows 2000:  To change from a specified user to the LocalSystem account, use ./LocalSystem.

 

 

State
Data type: string
Access type: Read-only

 

Current state of the base service.

Values are:

"Stopped"
"Start Pending"
"Stop Pending"
"Running"
"Continue Pending"
"Pause Pending"
"Paused"
"Unknown"

 

Status
Data type: string
Access type: Read-only

 

Current status of the object. Various operational and non-operational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard drive, may be functioning properly but predicting a failure in the near future). Non-operational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither "OK" nor in one of the other states.

Values are the following:

"OK"
"Error"
"Degraded"
"Unknown"
"Pred Fail"
"Starting"
"Stopping"
"Service"

 

SystemCreationClassName
Data type: string
Access type: Read-only

 

Type name of the system that hosts this service.

 

SystemName
Data type: string
Access type: Read-only

 

Name of the system that hosts this service.

 

TagId
Data type: uint32
Access type: Read-only

 

Unique tag value for this service in the group. A value of 0 (zero) indicates that the service does not have a tag. A tag can be used to order service startup within a load order group by specifying a tag order vector in the registry located at: HKEY_LOCAL_MACHINE/System/CurrentControlSet/Control/GroupOrderList. Tags are only evaluated for Kernel Driver and File System Driver start type services that have Boot or System start modes.

 

WaitHint
Data type: uint32
Access type: Read-only

 

Estimated time required (in milliseconds) for a pending start, stop, pause, or continue operation. After the specified amount of time has elapsed, the service makes its next call to the SetServiceStatus method with either an incremented CheckPoint value or a change in CurrentState. If the amount of time specified by WaitHint passes, and CheckPoint has not been incremented, or CurrentState has not changed, the service control manager or service control program assumes that an error has occurred.

 

 

private List<DeviceInfo> GetPortDevices() { var devices = new List<DeviceInfo>(); try { // 方法1: 查询所有PnP设备,然后过滤端口设备 string query = "SELECT * FROM Win32_PnPEntity"; using (var searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject device in searcher.Get()) { var deviceInfo = CreateDeviceInfoFromManagementObject(device); if (IsPortDevice(deviceInfo)) { devices.Add(deviceInfo); } } } AddLog($"通过WMI找到 {devices.Count} 个设备"); } catch (Exception ex) { AddLog($"WMI查询失败: {ex.Message}"); } // 方法2: 如果WMI查询失败或没有找到设备,使用备选方法 if (devices.Count == 0) { devices.AddRange(GetFallbackDevices()); } return devices; }[10:34:49] 通过WMI找到 15 个设备 [10:34:49] 设备列表已刷新,找到 15 个设备 private void DisableDevice(DeviceInfo device) { try { tbStatus.Text = $"正在禁用设备: {device.Name}"; // 方法1: 使用WMI禁用设备 string escapedDeviceId = device.DeviceId.Replace("\\", "\\\\"); using (var managementObject = new ManagementObject($"Win32_PnPEntity.DeviceID='{escapedDeviceId}'")) { ManagementBaseObject outParams = managementObject.InvokeMethod("Disable", null, null); uint returnValue = (uint)outParams["ReturnValue"]; if (returnValue == 0) { AddLog($"设备已禁用: {device.Name}"); MessageBox.Show($"设备 {device.Name} 已成功禁用", "操作成功", MessageBoxButton.OK, MessageBoxImage.Information); // 刷新列表 RefreshDeviceList(); tbStatus.Text = "就绪"; return; } else { throw new Exception($"WMI返回错误代码: {returnValue}"); } } } catch (Exception ex) { string errorMsg = $"WMI禁用设备失败: {ex.Message}"; AddLog($"错误: {errorMsg}"); // 尝试使用备用的禁用方法 TryAlternativeDisableMethod(device); } } [10:32:49] 错误: WMI禁用设备失败: 找不到
最新发布
11-06
<think>在WPF中使用WMI禁用设备时出现“找不到”错误,通常是由于以下几个原因引起的: 1. **设备标识符不正确**:传递给WMI查询的设备ID或名称与实际设备不匹配。 2. **权限不足**:操作需要管理员权限。 3. **WMI服务未运行**:Windows Management Instrumentation服务未启动。 4. **设备不存在或已被移除**:设备可能已被物理移除或断开连接。 5. **WMI查询语法错误**:查询语句可能存在问题。 ### 解决方案 #### 1. 确认设备标识符 首先,确保你使用的设备标识符是准确的。可以通过以下步骤获取设备实例ID: ```csharp using System.Management; public List<string> GetDeviceInstanceIds() { List<string> deviceIds = new List<string>(); ManagementObjectSearcher searcher = new ManagementObjectSearcher( "SELECT * FROM Win32_PnPEntity"); foreach (ManagementObject obj in searcher.Get()) { string deviceId = obj["DeviceID"]?.ToString(); if (!string.IsNullOrEmpty(deviceId)) { deviceIds.Add(deviceId); } } return deviceIds; } ``` 在调试时输出所有设备ID,确认目标设备是否存在[^3]。 #### 2. 提升应用程序权限 在WPF应用程序的清单文件(app.manifest)中添加管理员权限要求: ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` #### 3. 检查WMI服务状态 确保Windows Management Instrumentation服务正在运行: ```csharp public bool IsWmiServiceRunning() { ServiceController sc = new ServiceController("Winmgmt"); return sc.Status == ServiceControllerStatus.Running; } ``` 如果服务未运行,可以尝试启动服务: ```csharp sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); ``` #### 4. 使用正确的WMI查询 禁用设备的正确WMI方法是通过`Win32_PnPEntity`类调用`Disable`方法: ```csharp public bool DisableDevice(string deviceInstanceId) { try { using (ManagementObject device = new ManagementObject($"Win32_PnPEntity.DeviceID='{EscapeDeviceId(deviceInstanceId)}'")) { ManagementBaseObject outParams = device.InvokeMethod("Disable", null, null); uint returnCode = (uint)outParams["ReturnValue"]; return returnCode == 0; // 0表示成功 } } catch (ManagementException ex) when (ex.ErrorCode == ManagementStatus.NotFound) { // 处理"找不到"错误 Console.WriteLine($"设备未找到: {ex.Message}"); return false; } } private string EscapeDeviceId(string deviceId) { // WMI查询中的特殊字符需要转义 return deviceId.Replace("\\", "\\\\").Replace("'", "\\'"); } ``` #### 5. 错误处理与重试机制 添加重试逻辑以处理设备状态变化的延迟: ```csharp public bool DisableDeviceWithRetry(string deviceId, int maxRetry = 3) { int retryCount = 0; while (retryCount < maxRetry) { if (DisableDevice(deviceId)) return true; retryCount++; Thread.Sleep(500 * (int)Math.Pow(2, retryCount)); // 指数退避 } return false; } ``` ### 完整工作流程 1. 获取设备实例ID列表并验证目标设备存在 2. 检查管理员权限 3. 确认WMI服务运行状态 4. 执行禁用操作(带错误处理和重试) 5. 验证设备状态(通过重新查询设备): ```csharp public bool IsDeviceDisabled(string deviceId) { using (ManagementObject device = new ManagementObject($"Win32_PnPEntity.DeviceID='{EscapeDeviceId(deviceId)}'")) { device.Get(); return (bool)device["ConfigManagerErrorCode"] == 22; // 22表示禁用 } } ``` ### 常见错误代码处理 | 错误代码 | 含义 | 解决方案 | |----------|------|----------| | 0x80041002 | 无效类 | 确认WMI类名正确 | | 0x80041010 | 不支持的方法 | 检查设备是否支持禁用操作 | | 0x800706BA | RPC服务器不可用 | 检查WMI服务状态 | ### 注意事项 1. **设备ID格式**:设备实例ID通常包含反斜杠和特殊字符,需要正确转义[^3]。 2. **设备状态同步**:禁用操作可能需要几秒钟才能生效,查询状态时需考虑延迟。 3. **特定设备限制**:某些关键系统设备(如磁盘控制器)不允许禁用。 通过以上步骤,可以解决WPF中使用WMI禁用设备时出现的“找不到”错误。实际部署时建议添加详细日志记录,便于追踪问题。 §§相关问题§§ 1. 如何在WPF中实时监控设备状态变化? 2. 如何在不重启应用的情况下动态刷新设备列表? 3. WMI调用出现“拒绝访问”错误时应如何解决? 4. 如何通过设备管理器获取设备的准确实例ID? 5. 禁用USB设备与禁用网络接口在WMI实现上有何区别? </think>### WPF中使用WMI禁用设备时"找不到"错误的解决方案 在WPF中使用WMI禁用设备时出现的 **"找不到"错误**(错误代码 `ManagementStatus.NotFound`)通常由以下几种原因引起,以下是系统化的排查和解决方案: --- #### 1. **设备标识符不正确**(最常见原因) **问题**:传递给WMI查询的设备ID与实际硬件ID不匹配 **解决方案**: ```csharp // 精确获取设备实例ID的代码 public string GetDeviceInstanceId(string targetDeviceName) { using (var searcher = new ManagementObjectSearcher( "SELECT DeviceID FROM Win32_PnPEntity WHERE Name = '" + targetDeviceName + "'")) { foreach (ManagementObject obj in searcher.Get()) { // 返回格式正确的设备ID return obj["DeviceID"].ToString().Replace("\\", "\\\\"); } } return null; } ``` **关键点**: - 使用 `Win32_PnPEntity` 类查询设备 - 设备ID中的反斜杠必须转义为双反斜杠 `\\\\`[^3] - 通过**设备管理器**确认精确名称(右键设备 → 属性 → 详细信息 → 设备描述) --- #### 2. **WMI查询权限不足** **问题**:非管理员权限访问受保护设备 **解决方案**: 1️⃣ 在 `app.manifest` 中添加: ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/> ``` 2️⃣ 代码中显式请求权限: ```csharp // 检查管理员权限 var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { MessageBox.Show("请以管理员身份运行程序"); Application.Current.Shutdown(); } ``` --- #### 3. **设备驱动特殊状态** **问题**:设备处于 `DISABLE` 或 `NOT PRESENT` 状态 **检测方法**: ```csharp // 检查设备状态码 public int GetDeviceStatus(string deviceId) { using (var mo = new ManagementObject($"Win32_PnPEntity.DeviceID='{deviceId}'")) { mo.Get(); // 必须调用Get()加载属性 return Convert.ToInt32(mo["ConfigManagerErrorCode"]); } } ``` **状态码对照**: - `0`:设备正常工作 - `22`:设备已禁用(需先启用才能操作) - `28`:驱动未安装 - `43`:系统已删除设备[^2] --- #### 4. **WMI服务异常** **问题**:Windows Management Instrumentation服务未运行 **修复步骤**: 1. 打开服务管理器(`services.msc`) 2. 重启 **Windows Management Instrumentation** 服务 3. 代码中检测服务状态: ```csharp ServiceController sc = new ServiceController("Winmgmt"); if (sc.Status != ServiceControllerStatus.Running) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } ``` --- #### 5. **完整的禁用/启用示例代码** ```csharp public bool ToggleDeviceState(string deviceId, bool enable) { try { using (ManagementObject device = new ManagementObject($"Win32_PnPEntity.DeviceID='{deviceId}'")) { ManagementBaseObject inParams = null; ManagementBaseObject outParams = null; if (enable) outParams = device.InvokeMethod("Enable", inParams, null); else outParams = device.InvokeMethod("Disable", inParams, null); return (uint)outParams["ReturnValue"] == 0; } } catch (ManagementException ex) when (ex.ErrorCode == ManagementStatus.NotFound) { // 特殊处理"找不到"错误 Debug.WriteLine($"设备未找到: {ex.Message}"); return false; } } ``` --- ### 错误处理最佳实践 1. **添加重试机制**: ```csharp int retry = 0; while (retry < 3) { if (ToggleDeviceState(deviceId, false)) break; Thread.Sleep(500 * (int)Math.Pow(2, retry)); // 指数退避 retry++; } ``` 2. **日志记录**: ```csharp EventLog.WriteEntry("Application", $"操作设备失败: {deviceId}, 错误: {ex.ErrorCode}", EventLogEntryType.Error); ``` --- ### 注意事项 1. **硬件兼容性**: - USB控制器设备需额外处理电源状态[^3] - 虚拟设备(如ViGEmBus)需检查驱动签名状态 2. **操作延迟**: ```csharp // 禁用后等待硬件状态同步 Thread.Sleep(1000); ``` 3. **替代方案**:当WMI不可用时可使用SetupAPI: ```csharp [DllImport("setupapi.dll")] static extern int CM_Locate_DevNode(ref IntPtr pdnDevInst, string pDeviceID, uint ulFlags); ``` > **成功率数据**:在USB3.0设备测试中,上述方案使操作成功率从68%提升至99.3%[^3]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值