Suspend Process in C#
Here's my suggestion:
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200)
}
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
private static void SuspendProcess(int pid)
{
var process = Process.GetProcessById(pid); // throws exception if process does not exist
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
SuspendThread(pOpenThread);
CloseHandle(pOpenThread);
}
}
public static void ResumeProcess(int pid)
{
var process = Process.GetProcessById(pid);
if (process.ProcessName == string.Empty)
return;
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
var suspendCount = 0;
do
{
suspendCount = ResumeThread(pOpenThread);
} while (suspendCount > 0);
CloseHandle(pOpenThread);
}
}
How to check if a process is suspended? - Not not responding
Having established that the thread is waiting via it's ThreadState
, you can examine the WaitReason
property of the ProcessThread
and see if that says it's Suspended
.
Obviously, there are timing issues with performing tests such as these, since the other process is outside of your control.
How to create suspended process from c# without P/Invoke?
The only way to do this is with CreateProcess
. The .net Process
class does not offer the functionality. Either p/invoke CreateProcess
or use a mixed mode C++/CLI assembly to call the same.
Related Topics
An Implementation of the Fast Fourier Transform (Fft) in C#
No Output to Console from a Wpf Application
Cannot Use Ref or Out Parameter in Lambda Expressions
How to Detect the Character Encoding of a Text File
What Is Cool About Generics, Why Use Them
How to Convert a Gi-Normous Integer (In String Format) to Hex Format? (C#)
Using of Inotifypropertychanged
How to Get Memory Available or Used in C#
How to Start Winform App Minimized to Tray
How to Get Difference Between Two Dates in Year/Month/Week/Day
Coercing Floating-Point to Be Deterministic in .Net
Way to Have String.Replace Only Hit "Whole Words"
How to Store User Settings for a .Net Application
Searching for a Specific Jtoken by Name in a Jobject Hierarchy