Close process query handles

This commit is contained in:
rjc862003 committed 2026-10-01 23:49:22 -04:00
1 parent df9ab302ca
commit 2b29c15cf1
2 files changed
+36 -9

No files matched your search

@@ -21,10 +21,20 @@ public static class ProcessExtensions
{
int capacity = 2000;
StringBuilder builder = new(capacity);
nint ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id);
if (!QueryFullProcessImageName(ptr, 0, builder, ref capacity)) return string.Empty;
nint processHandle = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id);
if (processHandle == nint.Zero)
return string.Empty;
return builder.ToString();
try
{
return QueryFullProcessImageName(processHandle, 0, builder, ref capacity)
? builder.ToString()
: string.Empty;
}
finally
{
CloseHandle(processHandle);
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
@@ -33,9 +43,13 @@ public static class ProcessExtensions
[DllImport("kernel32.dll")]
private static extern nint OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint hObject);
[Flags]
private enum ProcessAccessFlags : uint
{
QueryLimitedInformation = 0x00001000
}
}
}
@@ -69,6 +69,10 @@ public static unsafe partial class ProcessMonitor
[LibraryImport("kernel32.dll")]
private static partial nint OpenProcess(ProcessAccessFlags processAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int processId);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseHandle(nint hObject);
[Flags]
private enum ProcessAccessFlags : uint
{
@@ -190,11 +194,20 @@ public static unsafe partial class ProcessMonitor
{
int capacity = byte.MaxValue;
char[] buffer = new char[capacity];
nint ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, processId);
nint processHandle = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, processId);
if (processHandle == nint.Zero)
return string.Empty;
return QueryFullProcessImageName(ptr, 0, buffer, ref capacity)
? new string(buffer, 0, capacity)
: string.Empty;
try
{
return QueryFullProcessImageName(processHandle, 0, buffer, ref capacity)
? new string(buffer, 0, capacity)
: string.Empty;
}
finally
{
CloseHandle(processHandle);
}
}
// This function generates the short form of process name.
@@ -228,4 +241,4 @@ public static unsafe partial class ProcessMonitor
private static uint GetEstimatedBufferSize(uint actualSize) => actualSize + (1024 * 10);
#endregion
}
}