RaUI/Source/MyDb/SysFuns/ProcessExt.cs

83 lines
2.6 KiB
C#
Raw Normal View History

using _SCREEN_CAPTURE;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ryCommon
{
/// <summary>
/// 进程相关接口
/// </summary>
public static class ProcessExt
{
[DllImport("psapi.dll")]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In][MarshalAs(UnmanagedType.U4)] int nSize);
/// <summary>
/// 获取进程路径
/// </summary>
/// <param name="process"></param>
/// <returns></returns>
public static string GetPath(this Process process)
{
if (process == null)
{
return "";
}
return GetPath(process.Id);
}
/// <summary>
/// 获取进程路径
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public static string GetPath(int pid)
{
var processHandle =WinAPI.Kernel32.OpenProcess(0x0400 | 0x0010, false, pid);
if (processHandle == IntPtr.Zero)
{
return null;
}
const int lengthSb = 4000;
var sb = new StringBuilder(lengthSb);
string result = "";
if (GetModuleFileNameEx(processHandle, IntPtr.Zero, sb, lengthSb) > 0)
{
result = sb.ToString();
}
WinAPI.Kernel32.CloseHandle(processHandle);
return result;
}
/// <summary>
/// 获取命令行
/// </summary>
/// <param name="processs"></param>
/// <returns></returns>
public static string GetCommandLines(this System.Diagnostics.Process processs)
{
if (processs == null) { return ""; }
return GetCommandLines(processs.Id);
}
/// <summary>
/// 获取命令行
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public static string GetCommandLines(int pid)
{
System.Management.ManagementObjectSearcher commandLineSearcher = new System.Management.ManagementObjectSearcher(
"SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + pid);
string commandLine = "";
foreach (var commandLineObject in commandLineSearcher.Get())
{
commandLine += (string)commandLineObject["CommandLine"];
}
commandLineSearcher.Dispose();
return commandLine;
}
}
}