我需要检查程序 ( xyz.exe) 是否正在运行,但仅限于当前用户。无论使用什么方法都不需要提升权限,并且必须运行速度快(因此 WMI 已被淘汰)。
Process.GetProcessesByName("xyz")返回所有登录用户的“xyz”结果...但我只关心当前用户。
有想法吗?
Geo*_*off 11
使用当前进程SessionId来过滤进程列表:
public static bool IsProcessRunningSameSession(string processName)
{
var currentSessionID = Process.GetCurrentProcess().SessionId;
return Process.GetProcessesByName(processName).Where(p => p.SessionId == currentSessionID).Any();
}
Run Code Online (Sandbox Code Playgroud)
我在这里找到了答案: http://dotbay.blogspot.com/2009/06/finding-owner-of-process-in-c.html
我会复制/粘贴它,以防博客被忽略。
////
// 'WindowsIdentity' Extension Method Demo:
// Enumerate all running processes with their associated Windows Identity
////
foreach (var p in Process.GetProcesses())
{
string processName;
try
{
processName = p.WindowsIdentity().Name;
}
catch (Exception ex)
{
processName = ex.Message; // Probably "Access is denied"
}
Console.WriteLine(p.ProcessName + " (" + processName + ")");
}
Run Code Online (Sandbox Code Playgroud)
这是对应的类:
//-----------------------------------------------------------------------
// <copyright file="ProcessExtensions.cs" company="DockOfTheBay">
// http://www.dotbay.be
// </copyright>
// <summary>Defines the ProcessExtensions class.</summary>
//-----------------------------------------------------------------------
namespace DockOfTheBay
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
/// <summary>
/// Extension Methods for the System.Diagnostics.Process Class.
/// </summary>
public static class ProcessExtensions
{
/// <summary>
/// Required to query an access token.
/// </summary>
private static uint TOKEN_QUERY = 0x0008;
/// <summary>
/// Returns the WindowsIdentity associated to a Process
/// </summary>
/// <param name="process">The Windows Process.</param>
/// <returns>The WindowsIdentity of the Process.</returns>
/// <remarks>Be prepared for 'Access Denied' Exceptions</remarks>
public static WindowsIdentity WindowsIdentity(this Process process)
{
IntPtr ph = IntPtr.Zero;
WindowsIdentity wi = null;
try
{
OpenProcessToken(process.Handle, TOKEN_QUERY, out ph);
wi = new WindowsIdentity(ph);
}
catch (Exception)
{
throw;
}
finally
{
if (ph != IntPtr.Zero)
{
CloseHandle(ph);
}
}
return wi;
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
}
}
Run Code Online (Sandbox Code Playgroud)