using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Management;
using System.Text;
using System.Linq;
namespace SteamTool.Core.Common
{
///
/// 为 类型提供扩展方法。
///
public static class ProcessExtensions
{
///
/// 获取一个正在运行的进程的命令行参数。
/// 与 一样,使用此方法获取的参数是包含应用程序路径的。
/// 关于 可参见:
/// .NET 命令行参数包含应用程序路径吗?https://blog.walterlv.com/post/when-will-the-command-line-args-contain-the-executable-path.html
///
/// 一个正在运行的进程。
/// 表示应用程序运行命令行参数的字符串。
public static string GetCommandLineArgs(this Process process)
{
if (process is null) throw new ArgumentNullException(nameof(process));
try
{
return GetCommandLineArgsCore();
}
catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
{
// 没有对该进程的安全访问权限。
return string.Empty;
}
catch (InvalidOperationException)
{
// 进程已退出。
return string.Empty;
}
string GetCommandLineArgsCore()
{
using var searcher = new ManagementObjectSearcher(
"SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id);
using var objects = searcher.Get();
var @object = objects.Cast().SingleOrDefault();
return @object?["CommandLine"]?.ToString() ?? "";
}
}
}
}