Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Decompiled with JetBrains decompiler
- // Type: System.Diagnostics.Process
- // Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- // MVID: 988FA076-10C9-4365-AE6D-295A6AA379FE
- // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll
- using Microsoft.Win32;
- using Microsoft.Win32.SafeHandles;
- using System.Collections;
- using System.ComponentModel;
- using System.ComponentModel.Design;
- using System.Globalization;
- using System.IO;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Permissions;
- using System.Text;
- using System.Threading;
- namespace System.Diagnostics
- {
- /// <summary>Provides access to local and remote processes and enables you to start and stop local system processes.To browse the .NET Framework source code for this type, see the Reference Source.</summary>
- [MonitoringDescription("ProcessDesc")]
- [DefaultEvent("Exited")]
- [DefaultProperty("StartInfo")]
- [Designer("System.Diagnostics.Design.ProcessDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
- [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
- [HostProtection(SecurityAction.LinkDemand, ExternalProcessMgmt = true, SelfAffectingProcessMgmt = true, SharedState = true, Synchronization = true)]
- [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
- public class Process : Component
- {
- private static object s_CreateProcessLock = new object();
- private static SafeFileHandle InvalidPipeHandle = new SafeFileHandle(IntPtr.Zero, false);
- internal static TraceSwitch processTracing = (TraceSwitch) null;
- private bool haveProcessId;
- private int processId;
- private bool haveProcessHandle;
- private SafeProcessHandle m_processHandle;
- private bool isRemoteMachine;
- private string machineName;
- private ProcessInfo processInfo;
- private int m_processAccess;
- private ProcessThreadCollection threads;
- private ProcessModuleCollection modules;
- private bool haveMainWindow;
- private IntPtr mainWindowHandle;
- private string mainWindowTitle;
- private bool haveWorkingSetLimits;
- private IntPtr minWorkingSet;
- private IntPtr maxWorkingSet;
- private bool haveProcessorAffinity;
- private IntPtr processorAffinity;
- private bool havePriorityClass;
- private ProcessPriorityClass priorityClass;
- private ProcessStartInfo startInfo;
- private bool watchForExit;
- private bool watchingForExit;
- private EventHandler onExited;
- private bool exited;
- private int exitCode;
- private bool signaled;
- private DateTime exitTime;
- private bool haveExitTime;
- private bool responding;
- private bool haveResponding;
- private bool priorityBoostEnabled;
- private bool havePriorityBoostEnabled;
- private bool raisedOnExited;
- private RegisteredWaitHandle registeredWaitHandle;
- private WaitHandle waitHandle;
- private ISynchronizeInvoke synchronizingObject;
- private StreamReader standardOutput;
- private StreamWriter standardInput;
- private StreamReader standardError;
- private OperatingSystem operatingSystem;
- private bool disposed;
- private Process.StreamReadMode outputStreamReadMode;
- private Process.StreamReadMode errorStreamReadMode;
- internal AsyncStreamReader output;
- internal AsyncStreamReader error;
- internal bool pendingOutputRead;
- internal bool pendingErrorRead;
- /// <summary>Occurs each time an application writes a line to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream. </summary>
- [Browsable(true)]
- [MonitoringDescription("ProcessAssociated")]
- public event DataReceivedEventHandler OutputDataReceived;
- /// <summary>Occurs when an application writes to its redirected <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</summary>
- [Browsable(true)]
- [MonitoringDescription("ProcessAssociated")]
- public event DataReceivedEventHandler ErrorDataReceived;
- /// <summary>Initializes a new instance of the <see cref="T:System.Diagnostics.Process" /> class.</summary>
- public Process()
- {
- this.machineName = ".";
- this.outputStreamReadMode = Process.StreamReadMode.undefined;
- this.errorStreamReadMode = Process.StreamReadMode.undefined;
- this.m_processAccess = 2035711;
- }
- private Process(
- string machineName,
- bool isRemoteMachine,
- int processId,
- ProcessInfo processInfo)
- {
- this.processInfo = processInfo;
- this.machineName = machineName;
- this.isRemoteMachine = isRemoteMachine;
- this.processId = processId;
- this.haveProcessId = true;
- this.outputStreamReadMode = Process.StreamReadMode.undefined;
- this.errorStreamReadMode = Process.StreamReadMode.undefined;
- this.m_processAccess = 2035711;
- }
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessAssociated")]
- private bool Associated
- {
- get
- {
- if (!this.haveProcessId)
- return this.haveProcessHandle;
- return true;
- }
- }
- /// <summary>Gets the base priority of the associated process.</summary>
- /// <returns>The base priority, which is computed from the <see cref="P:System.Diagnostics.Process.PriorityClass" /> of the associated process.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set the <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.InvalidOperationException">The process has exited.-or- The process has not started, so there is no process ID. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessBasePriority")]
- public int BasePriority
- {
- get
- {
- this.EnsureState(Process.State.HaveProcessInfo);
- return this.processInfo.basePriority;
- }
- }
- /// <summary>Gets the value that the associated process specified when it terminated.</summary>
- /// <returns>The code that the associated process specified when it terminated.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process has not exited.-or- The process <see cref="P:System.Diagnostics.Process.Handle" /> is not valid. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.ExitCode" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessExitCode")]
- public int ExitCode
- {
- get
- {
- this.EnsureState(Process.State.Exited);
- return this.exitCode;
- }
- }
- /// <summary>Gets a value indicating whether the associated process has been terminated.</summary>
- /// <returns>
- /// <see langword="true" /> if the operating system process referenced by the <see cref="T:System.Diagnostics.Process" /> component has terminated; otherwise, <see langword="false" />.</returns>
- /// <exception cref="T:System.InvalidOperationException">There is no process associated with the object. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">The exit code for the process could not be retrieved. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.HasExited" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessTerminated")]
- public bool HasExited
- {
- get
- {
- if (!this.exited)
- {
- this.EnsureState(Process.State.Associated);
- SafeProcessHandle safeProcessHandle = (SafeProcessHandle) null;
- try
- {
- safeProcessHandle = this.GetProcessHandle(1049600, false);
- if (safeProcessHandle.IsInvalid)
- {
- this.exited = true;
- }
- else
- {
- int exitCode;
- if (Microsoft.Win32.NativeMethods.GetExitCodeProcess(safeProcessHandle, out exitCode) && exitCode != 259)
- {
- this.exited = true;
- this.exitCode = exitCode;
- }
- else
- {
- if (!this.signaled)
- {
- ProcessWaitHandle processWaitHandle = (ProcessWaitHandle) null;
- try
- {
- processWaitHandle = new ProcessWaitHandle(safeProcessHandle);
- this.signaled = processWaitHandle.WaitOne(0, false);
- }
- finally
- {
- processWaitHandle?.Close();
- }
- }
- if (this.signaled)
- {
- if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(safeProcessHandle, out exitCode))
- throw new Win32Exception();
- this.exited = true;
- this.exitCode = exitCode;
- }
- }
- }
- }
- finally
- {
- this.ReleaseProcessHandle(safeProcessHandle);
- }
- if (this.exited)
- this.RaiseOnExited();
- }
- return this.exited;
- }
- }
- private ProcessThreadTimes GetProcessTimes()
- {
- ProcessThreadTimes processThreadTimes = new ProcessThreadTimes();
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- int access = 1024;
- if (EnvironmentHelpers.IsWindowsVistaOrAbove())
- access = 4096;
- handle = this.GetProcessHandle(access, false);
- if (handle.IsInvalid)
- throw new InvalidOperationException(SR.GetString("ProcessHasExited", (object) this.processId.ToString((IFormatProvider) CultureInfo.CurrentCulture)));
- if (!Microsoft.Win32.NativeMethods.GetProcessTimes(handle, out processThreadTimes.create, out processThreadTimes.exit, out processThreadTimes.kernel, out processThreadTimes.user))
- throw new Win32Exception();
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- return processThreadTimes;
- }
- /// <summary>Gets the time that the associated process exited.</summary>
- /// <returns>A <see cref="T:System.DateTime" /> that indicates when the associated process was terminated.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.ExitTime" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessExitTime")]
- public DateTime ExitTime
- {
- get
- {
- if (!this.haveExitTime)
- {
- this.EnsureState(Process.State.IsNt | Process.State.Exited);
- this.exitTime = this.GetProcessTimes().ExitTime;
- this.haveExitTime = true;
- }
- return this.exitTime;
- }
- }
- /// <summary>Gets the native handle of the associated process.</summary>
- /// <returns>The handle that the operating system assigned to the associated process when the process was started. The system uses this handle to keep track of process attributes.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process has not been started or has exited. The <see cref="P:System.Diagnostics.Process.Handle" /> property cannot be read because there is no process associated with this <see cref="T:System.Diagnostics.Process" /> instance.-or- The <see cref="T:System.Diagnostics.Process" /> instance has been attached to a running process but you do not have the necessary permissions to get a handle with full access rights. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.Handle" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessHandle")]
- public IntPtr Handle
- {
- get
- {
- this.EnsureState(Process.State.Associated);
- return this.OpenProcessHandle(this.m_processAccess).DangerousGetHandle();
- }
- }
- /// <summary>Gets the native handle to this process.</summary>
- /// <returns>The native handle to this process.</returns>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public SafeProcessHandle SafeHandle
- {
- get
- {
- this.EnsureState(Process.State.Associated);
- return this.OpenProcessHandle(this.m_processAccess);
- }
- }
- /// <summary>Gets the number of handles opened by the process.</summary>
- /// <returns>The number of operating system handles the process has opened.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set the <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessHandleCount")]
- public int HandleCount
- {
- get
- {
- this.EnsureState(Process.State.HaveProcessInfo);
- return this.processInfo.handleCount;
- }
- }
- /// <summary>Gets the unique identifier for the associated process.</summary>
- /// <returns>The system-generated unique identifier of the process that is referenced by this <see cref="T:System.Diagnostics.Process" /> instance.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process's <see cref="P:System.Diagnostics.Process.Id" /> property has not been set.-or- There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set the <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessId")]
- public int Id
- {
- get
- {
- this.EnsureState(Process.State.HaveId);
- return this.processId;
- }
- }
- /// <summary>Gets the name of the computer the associated process is running on.</summary>
- /// <returns>The name of the computer that the associated process is running on.</returns>
- /// <exception cref="T:System.InvalidOperationException">There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMachineName")]
- public string MachineName
- {
- get
- {
- this.EnsureState(Process.State.Associated);
- return this.machineName;
- }
- }
- /// <summary>Gets the window handle of the main window of the associated process.</summary>
- /// <returns>The system-generated window handle of the main window of the associated process.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.MainWindowHandle" /> is not defined because the process has exited. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.MainWindowHandle" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMainWindowHandle")]
- public IntPtr MainWindowHandle
- {
- get
- {
- if (!this.haveMainWindow)
- {
- this.EnsureState(Process.State.HaveId | Process.State.IsLocal);
- this.mainWindowHandle = ProcessManager.GetMainWindowHandle(this.processId);
- if (this.mainWindowHandle != (IntPtr) 0)
- this.haveMainWindow = true;
- else
- this.EnsureState(Process.State.HaveProcessInfo);
- }
- return this.mainWindowHandle;
- }
- }
- /// <summary>Gets the caption of the main window of the process.</summary>
- /// <returns>The main window title of the process.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.MainWindowTitle" /> property is not defined because the process has exited. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.MainWindowTitle" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMainWindowTitle")]
- public string MainWindowTitle
- {
- get
- {
- if (this.mainWindowTitle == null)
- {
- IntPtr mainWindowHandle = this.MainWindowHandle;
- if (mainWindowHandle == (IntPtr) 0)
- {
- this.mainWindowTitle = string.Empty;
- }
- else
- {
- StringBuilder lpString = new StringBuilder(Microsoft.Win32.NativeMethods.GetWindowTextLength(new HandleRef((object) this, mainWindowHandle)) * 2);
- Microsoft.Win32.NativeMethods.GetWindowText(new HandleRef((object) this, mainWindowHandle), lpString, lpString.Capacity);
- this.mainWindowTitle = lpString.ToString();
- }
- }
- return this.mainWindowTitle;
- }
- }
- /// <summary>Gets the main module for the associated process.</summary>
- /// <returns>The <see cref="T:System.Diagnostics.ProcessModule" /> that was used to start the process.</returns>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.MainModule" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">A 32-bit process is trying to access the modules of a 64-bit process.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.-or- The process has exited. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMainModule")]
- public ProcessModule MainModule
- {
- get
- {
- if (this.OperatingSystem.Platform == PlatformID.Win32NT)
- {
- this.EnsureState(Process.State.HaveId | Process.State.IsLocal);
- return new ProcessModule(NtProcessManager.GetFirstModuleInfo(this.processId));
- }
- ProcessModuleCollection modules = this.Modules;
- this.EnsureState(Process.State.HaveProcessInfo);
- foreach (ProcessModule processModule in (ReadOnlyCollectionBase) modules)
- {
- if (processModule.moduleInfo.Id == this.processInfo.mainModuleId)
- return processModule;
- }
- return (ProcessModule) null;
- }
- }
- /// <summary>Gets or sets the maximum allowable working set size, in bytes, for the associated process.</summary>
- /// <returns>The maximum working set size that is allowed in memory for the process, in bytes.</returns>
- /// <exception cref="T:System.ArgumentException">The maximum working set size is invalid. It must be greater than or equal to the minimum working set size.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">Working set information cannot be retrieved from the associated process resource.-or- The process identifier or process handle is zero because the process has not been started. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.MaxWorkingSet" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.</exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.-or- The process has exited. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMaxWorkingSet")]
- public IntPtr MaxWorkingSet
- {
- get
- {
- this.EnsureWorkingSetLimits();
- return this.maxWorkingSet;
- }
- set
- {
- this.SetWorkingSetLimits((object) null, (object) value);
- }
- }
- /// <summary>Gets or sets the minimum allowable working set size, in bytes, for the associated process.</summary>
- /// <returns>The minimum working set size that is required in memory for the process, in bytes.</returns>
- /// <exception cref="T:System.ArgumentException">The minimum working set size is invalid. It must be less than or equal to the maximum working set size.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">Working set information cannot be retrieved from the associated process resource.-or- The process identifier or process handle is zero because the process has not been started. </exception>
- /// <exception cref="T:System.NotSupportedException">You are trying to access the <see cref="P:System.Diagnostics.Process.MinWorkingSet" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.-or- The process has exited.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessMinWorkingSet")]
- public IntPtr MinWorkingSet
- {
- get
- {
- this.EnsureWorkingSetLimits();
- return this.minWorkingSet;
- }
- set
- {
- this.SetWorkingSetLimits((object) value, (object) null);
- }
- }
- /// <summary>Gets the modules that have been loaded by the associated process.</summary>
- /// <returns>An array of type <see cref="T:System.Diagnostics.ProcessModule" /> that represents the modules that have been loaded by the associated process.</returns>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.Modules" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">You are attempting to access the <see cref="P:System.Diagnostics.Process.Modules" /> property for either the system process or the idle process. These processes do not have modules.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessModules")]
- public ProcessModuleCollection Modules
- {
- get
- {
- if (this.modules == null)
- {
- this.EnsureState(Process.State.HaveId | Process.State.IsLocal);
- ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(this.processId);
- ProcessModule[] processModules = new ProcessModule[moduleInfos.Length];
- for (int index = 0; index < moduleInfos.Length; ++index)
- processModules[index] = new ProcessModule(moduleInfos[index]);
- this.modules = new ProcessModuleCollection(processModules);
- }
- return this.modules;
- }
- }
- /// <summary>Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of memory, in bytes, the system has allocated for the associated process that cannot be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessNonpagedSystemMemorySize")]
- public int NonpagedSystemMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.poolNonpagedBytes;
- }
- }
- /// <summary>Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of system memory, in bytes, allocated for the associated process that cannot be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessNonpagedSystemMemorySize")]
- [ComVisible(false)]
- public long NonpagedSystemMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.poolNonpagedBytes;
- }
- }
- /// <summary>Gets the amount of paged memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of memory, in bytes, allocated by the associated process that can be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPagedMemorySize")]
- public int PagedMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.pageFileBytes;
- }
- }
- /// <summary>Gets the amount of paged memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of memory, in bytes, allocated in the virtual memory paging file for the associated process.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPagedMemorySize")]
- [ComVisible(false)]
- public long PagedMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.pageFileBytes;
- }
- }
- /// <summary>Gets the amount of pageable system memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of memory, in bytes, the system has allocated for the associated process that can be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPagedSystemMemorySize")]
- public int PagedSystemMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.poolPagedBytes;
- }
- }
- /// <summary>Gets the amount of pageable system memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of system memory, in bytes, allocated for the associated process that can be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPagedSystemMemorySize")]
- [ComVisible(false)]
- public long PagedSystemMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.poolPagedBytes;
- }
- }
- /// <summary>Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated process.</summary>
- /// <returns>The maximum amount of memory, in bytes, allocated by the associated process that could be written to the virtual memory paging file.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakPagedMemorySize")]
- public int PeakPagedMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.pageFileBytesPeak;
- }
- }
- /// <summary>Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated process.</summary>
- /// <returns>The maximum amount of memory, in bytes, allocated in the virtual memory paging file for the associated process since it was started.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakPagedMemorySize")]
- [ComVisible(false)]
- public long PeakPagedMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.pageFileBytesPeak;
- }
- }
- /// <summary>Gets the peak working set size for the associated process, in bytes.</summary>
- /// <returns>The maximum amount of physical memory that the associated process has required all at once, in bytes.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakWorkingSet")]
- public int PeakWorkingSet
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.workingSetPeak;
- }
- }
- /// <summary>Gets the maximum amount of physical memory, in bytes, used by the associated process.</summary>
- /// <returns>The maximum amount of physical memory, in bytes, allocated for the associated process since it was started.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakWorkingSet")]
- [ComVisible(false)]
- public long PeakWorkingSet64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.workingSetPeak;
- }
- }
- /// <summary>Gets the maximum amount of virtual memory, in bytes, used by the associated process.</summary>
- /// <returns>The maximum amount of virtual memory, in bytes, that the associated process has requested.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakVirtualMemorySize")]
- public int PeakVirtualMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.virtualBytesPeak;
- }
- }
- /// <summary>Gets the maximum amount of virtual memory, in bytes, used by the associated process.</summary>
- /// <returns>The maximum amount of virtual memory, in bytes, allocated for the associated process since it was started.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPeakVirtualMemorySize")]
- [ComVisible(false)]
- public long PeakVirtualMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.virtualBytesPeak;
- }
- }
- private OperatingSystem OperatingSystem
- {
- get
- {
- if (this.operatingSystem == null)
- this.operatingSystem = Environment.OSVersion;
- return this.operatingSystem;
- }
- }
- /// <summary>Gets or sets a value indicating whether the associated process priority should temporarily be boosted by the operating system when the main window has the focus.</summary>
- /// <returns>
- /// <see langword="true" /> if dynamic boosting of the process priority should take place for a process when it is taken out of the wait state; otherwise, <see langword="false" />. The default is <see langword="false" />.</returns>
- /// <exception cref="T:System.ComponentModel.Win32Exception">Priority boost information could not be retrieved from the associated process resource. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.-or- The process identifier or process handle is zero. (The process has not been started.) </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.PriorityBoostEnabled" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPriorityBoostEnabled")]
- public bool PriorityBoostEnabled
- {
- get
- {
- this.EnsureState(Process.State.IsNt);
- if (!this.havePriorityBoostEnabled)
- {
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1024);
- bool disabled = false;
- if (!Microsoft.Win32.NativeMethods.GetProcessPriorityBoost(handle, out disabled))
- throw new Win32Exception();
- this.priorityBoostEnabled = !disabled;
- this.havePriorityBoostEnabled = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- return this.priorityBoostEnabled;
- }
- set
- {
- this.EnsureState(Process.State.IsNt);
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(512);
- if (!Microsoft.Win32.NativeMethods.SetProcessPriorityBoost(handle, !value))
- throw new Win32Exception();
- this.priorityBoostEnabled = value;
- this.havePriorityBoostEnabled = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- }
- /// <summary>Gets or sets the overall priority category for the associated process.</summary>
- /// <returns>The priority category for the associated process, from which the <see cref="P:System.Diagnostics.Process.BasePriority" /> of the process is calculated.</returns>
- /// <exception cref="T:System.ComponentModel.Win32Exception">Process priority information could not be set or retrieved from the associated process resource.-or- The process identifier or process handle is zero. (The process has not been started.) </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.PriorityClass" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> is not available.</exception>
- /// <exception cref="T:System.PlatformNotSupportedException">You have set the <see cref="P:System.Diagnostics.Process.PriorityClass" /> to <see langword="AboveNormal" /> or <see langword="BelowNormal" /> when using Windows 98 or Windows Millennium Edition (Windows Me). These platforms do not support those values for the priority class. </exception>
- /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">Priority class cannot be set because it does not use a valid value, as defined in the <see cref="T:System.Diagnostics.ProcessPriorityClass" /> enumeration.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPriorityClass")]
- public ProcessPriorityClass PriorityClass
- {
- get
- {
- if (!this.havePriorityClass)
- {
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1024);
- int priorityClass = Microsoft.Win32.NativeMethods.GetPriorityClass(handle);
- if (priorityClass == 0)
- throw new Win32Exception();
- this.priorityClass = (ProcessPriorityClass) priorityClass;
- this.havePriorityClass = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- return this.priorityClass;
- }
- set
- {
- if (!Enum.IsDefined(typeof (ProcessPriorityClass), (object) value))
- throw new InvalidEnumArgumentException(nameof (value), (int) value, typeof (ProcessPriorityClass));
- if ((value & (ProcessPriorityClass.BelowNormal | ProcessPriorityClass.AboveNormal)) != (ProcessPriorityClass) 0 && (this.OperatingSystem.Platform != PlatformID.Win32NT || this.OperatingSystem.Version.Major < 5))
- throw new PlatformNotSupportedException(SR.GetString("PriorityClassNotSupported"), (Exception) null);
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(512);
- if (!Microsoft.Win32.NativeMethods.SetPriorityClass(handle, (int) value))
- throw new Win32Exception();
- this.priorityClass = value;
- this.havePriorityClass = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- }
- /// <summary>Gets the amount of private memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The number of bytes allocated by the associated process that cannot be shared with other processes.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPrivateMemorySize")]
- public int PrivateMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.privateBytes;
- }
- }
- /// <summary>Gets the amount of private memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of memory, in bytes, allocated for the associated process that cannot be shared with other processes.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPrivateMemorySize")]
- [ComVisible(false)]
- public long PrivateMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.privateBytes;
- }
- }
- /// <summary>Gets the privileged processor time for this process.</summary>
- /// <returns>A <see cref="T:System.TimeSpan" /> that indicates the amount of time that the process has spent running code inside the operating system core.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.PrivilegedProcessorTime" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessPrivilegedProcessorTime")]
- public TimeSpan PrivilegedProcessorTime
- {
- get
- {
- this.EnsureState(Process.State.IsNt);
- return this.GetProcessTimes().PrivilegedProcessorTime;
- }
- }
- /// <summary>Gets the name of the process.</summary>
- /// <returns>The name that the system uses to identify the process to the user.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process does not have an identifier, or no process is associated with the <see cref="T:System.Diagnostics.Process" />.-or- The associated process has exited. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.NotSupportedException">The process is not on this computer.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessProcessName")]
- public string ProcessName
- {
- get
- {
- this.EnsureState(Process.State.HaveProcessInfo);
- if (this.processInfo.processName.Length == 15 && ProcessManager.IsNt && ProcessManager.IsOSOlderThanXP)
- {
- if (!this.isRemoteMachine)
- {
- try
- {
- string moduleName = this.MainModule.ModuleName;
- if (moduleName != null)
- this.processInfo.processName = Path.ChangeExtension(Path.GetFileName(moduleName), (string) null);
- }
- catch (Exception ex)
- {
- }
- }
- }
- return this.processInfo.processName;
- }
- }
- /// <summary>Gets or sets the processors on which the threads in this process can be scheduled to run.</summary>
- /// <returns>A bitmask representing the processors that the threads in the associated process can run on. The default depends on the number of processors on the computer. The default value is 2 n -1, where n is the number of processors.</returns>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// <see cref="P:System.Diagnostics.Process.ProcessorAffinity" /> information could not be set or retrieved from the associated process resource.-or- The process identifier or process handle is zero. (The process has not been started.) </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.ProcessorAffinity" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process <see cref="P:System.Diagnostics.Process.Id" /> was not available.-or- The process has exited. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessProcessorAffinity")]
- public IntPtr ProcessorAffinity
- {
- get
- {
- if (!this.haveProcessorAffinity)
- {
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1024);
- IntPtr processMask;
- IntPtr systemMask;
- if (!Microsoft.Win32.NativeMethods.GetProcessAffinityMask(handle, out processMask, out systemMask))
- throw new Win32Exception();
- this.processorAffinity = processMask;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- this.haveProcessorAffinity = true;
- }
- return this.processorAffinity;
- }
- set
- {
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(512);
- if (!Microsoft.Win32.NativeMethods.SetProcessAffinityMask(handle, value))
- throw new Win32Exception();
- this.processorAffinity = value;
- this.haveProcessorAffinity = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- }
- /// <summary>Gets a value indicating whether the user interface of the process is responding.</summary>
- /// <returns>
- /// <see langword="true" /> if the user interface of the associated process is responding to the system; otherwise, <see langword="false" />.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.InvalidOperationException">There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object. </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.Responding" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessResponding")]
- public bool Responding
- {
- get
- {
- if (!this.haveResponding)
- {
- IntPtr mainWindowHandle = this.MainWindowHandle;
- IntPtr pdwResult;
- this.responding = mainWindowHandle == (IntPtr) 0 || Microsoft.Win32.NativeMethods.SendMessageTimeout(new HandleRef((object) this, mainWindowHandle), 0, IntPtr.Zero, IntPtr.Zero, 2, 5000, out pdwResult) != (IntPtr) 0;
- }
- return this.responding;
- }
- }
- /// <summary>Gets the Terminal Services session identifier for the associated process.</summary>
- /// <returns>The Terminal Services session identifier for the associated process.</returns>
- /// <exception cref="T:System.NullReferenceException">There is no session associated with this process.</exception>
- /// <exception cref="T:System.InvalidOperationException">There is no process associated with this session identifier.-or-The associated process is not on this machine. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The <see cref="P:System.Diagnostics.Process.SessionId" /> property is not supported on Windows 98.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessSessionId")]
- public int SessionId
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.sessionId;
- }
- }
- /// <summary>Gets or sets the properties to pass to the <see cref="M:System.Diagnostics.Process.Start" /> method of the <see cref="T:System.Diagnostics.Process" />.</summary>
- /// <returns>The <see cref="T:System.Diagnostics.ProcessStartInfo" /> that represents the data with which to start the process. These arguments include the name of the executable file or document used to start the process.</returns>
- /// <exception cref="T:System.ArgumentNullException">The value that specifies the <see cref="P:System.Diagnostics.Process.StartInfo" /> is <see langword="null" />. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
- [MonitoringDescription("ProcessStartInfo")]
- public ProcessStartInfo StartInfo
- {
- get
- {
- if (this.startInfo == null)
- this.startInfo = new ProcessStartInfo(this);
- return this.startInfo;
- }
- set
- {
- if (value == null)
- throw new ArgumentNullException(nameof (value));
- this.startInfo = value;
- }
- }
- /// <summary>Gets the time that the associated process was started.</summary>
- /// <returns>An object that indicates when the process started. An exception is thrown if the process is not running.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.StartTime" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process has exited.-or-The process has not been started.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">An error occurred in the call to the Windows function.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessStartTime")]
- public DateTime StartTime
- {
- get
- {
- this.EnsureState(Process.State.IsNt);
- return this.GetProcessTimes().StartTime;
- }
- }
- /// <summary>Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event.</summary>
- /// <returns>The <see cref="T:System.ComponentModel.ISynchronizeInvoke" /> used to marshal event handler calls that are issued as a result of an <see cref="E:System.Diagnostics.Process.Exited" /> event on the process.</returns>
- [Browsable(false)]
- [DefaultValue(null)]
- [MonitoringDescription("ProcessSynchronizingObject")]
- public ISynchronizeInvoke SynchronizingObject
- {
- get
- {
- if (this.synchronizingObject == null && this.DesignMode)
- {
- IDesignerHost service = (IDesignerHost) this.GetService(typeof (IDesignerHost));
- if (service != null)
- {
- object rootComponent = (object) service.RootComponent;
- if (rootComponent != null && rootComponent is ISynchronizeInvoke)
- this.synchronizingObject = (ISynchronizeInvoke) rootComponent;
- }
- }
- return this.synchronizingObject;
- }
- set
- {
- this.synchronizingObject = value;
- }
- }
- /// <summary>Gets the set of threads that are running in the associated process.</summary>
- /// <returns>An array of type <see cref="T:System.Diagnostics.ProcessThread" /> representing the operating system threads currently running in the associated process.</returns>
- /// <exception cref="T:System.SystemException">The process does not have an <see cref="P:System.Diagnostics.Process.Id" />, or no process is associated with the <see cref="T:System.Diagnostics.Process" /> instance.-or- The associated process has exited. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessThreads")]
- public ProcessThreadCollection Threads
- {
- get
- {
- if (this.threads == null)
- {
- this.EnsureState(Process.State.HaveProcessInfo);
- int count = this.processInfo.threadInfoList.Count;
- ProcessThread[] processThreads = new ProcessThread[count];
- for (int index = 0; index < count; ++index)
- processThreads[index] = new ProcessThread(this.isRemoteMachine, (ThreadInfo) this.processInfo.threadInfoList[index]);
- this.threads = new ProcessThreadCollection(processThreads);
- }
- return this.threads;
- }
- }
- /// <summary>Gets the total processor time for this process.</summary>
- /// <returns>A <see cref="T:System.TimeSpan" /> that indicates the amount of time that the associated process has spent utilizing the CPU. This value is the sum of the <see cref="P:System.Diagnostics.Process.UserProcessorTime" /> and the <see cref="P:System.Diagnostics.Process.PrivilegedProcessorTime" />.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.TotalProcessorTime" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessTotalProcessorTime")]
- public TimeSpan TotalProcessorTime
- {
- get
- {
- this.EnsureState(Process.State.IsNt);
- return this.GetProcessTimes().TotalProcessorTime;
- }
- }
- /// <summary>Gets the user processor time for this process.</summary>
- /// <returns>A <see cref="T:System.TimeSpan" /> that indicates the amount of time that the associated process has spent running code inside the application portion of the process (not inside the operating system core).</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to access the <see cref="P:System.Diagnostics.Process.UserProcessorTime" /> property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer. </exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessUserProcessorTime")]
- public TimeSpan UserProcessorTime
- {
- get
- {
- this.EnsureState(Process.State.IsNt);
- return this.GetProcessTimes().UserProcessorTime;
- }
- }
- /// <summary>Gets the size of the process's virtual memory, in bytes.</summary>
- /// <returns>The amount of virtual memory, in bytes, that the associated process has requested.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessVirtualMemorySize")]
- public int VirtualMemorySize
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.virtualBytes;
- }
- }
- /// <summary>Gets the amount of the virtual memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of virtual memory, in bytes, allocated for the associated process.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessVirtualMemorySize")]
- [ComVisible(false)]
- public long VirtualMemorySize64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.virtualBytes;
- }
- }
- /// <summary>Gets or sets whether the <see cref="E:System.Diagnostics.Process.Exited" /> event should be raised when the process terminates.</summary>
- /// <returns>
- /// <see langword="true" /> if the <see cref="E:System.Diagnostics.Process.Exited" /> event should be raised when the associated process is terminated (through either an exit or a call to <see cref="M:System.Diagnostics.Process.Kill" />); otherwise, <see langword="false" />. The default is <see langword="false" />.</returns>
- [Browsable(false)]
- [DefaultValue(false)]
- [MonitoringDescription("ProcessEnableRaisingEvents")]
- public bool EnableRaisingEvents
- {
- get
- {
- return this.watchForExit;
- }
- set
- {
- if (value == this.watchForExit)
- return;
- if (this.Associated)
- {
- if (value)
- {
- this.OpenProcessHandle();
- this.EnsureWatchingForExit();
- }
- else
- this.StopWatchingForExit();
- }
- this.watchForExit = value;
- }
- }
- /// <summary>Gets a stream used to write the input of the application.</summary>
- /// <returns>A <see cref="T:System.IO.StreamWriter" /> that can be used to write the standard input stream of the application.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.StandardInput" /> stream has not been defined because <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardInput" /> is set to <see langword="false" />. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessStandardInput")]
- public StreamWriter StandardInput
- {
- get
- {
- if (this.standardInput == null)
- throw new InvalidOperationException(SR.GetString("CantGetStandardIn"));
- return this.standardInput;
- }
- }
- /// <summary>Gets a stream used to read the textual output of the application.</summary>
- /// <returns>A <see cref="T:System.IO.StreamReader" /> that can be used to read the standard output stream of the application.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream has not been defined for redirection; ensure <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardOutput" /> is set to <see langword="true" /> and <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> is set to <see langword="false" />.- or - The <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream has been opened for asynchronous read operations with <see cref="M:System.Diagnostics.Process.BeginOutputReadLine" />. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessStandardOutput")]
- public StreamReader StandardOutput
- {
- get
- {
- if (this.standardOutput == null)
- throw new InvalidOperationException(SR.GetString("CantGetStandardOut"));
- if (this.outputStreamReadMode == Process.StreamReadMode.undefined)
- this.outputStreamReadMode = Process.StreamReadMode.syncMode;
- else if (this.outputStreamReadMode != Process.StreamReadMode.syncMode)
- throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
- return this.standardOutput;
- }
- }
- /// <summary>Gets a stream used to read the error output of the application.</summary>
- /// <returns>A <see cref="T:System.IO.StreamReader" /> that can be used to read the standard error stream of the application.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.StandardError" /> stream has not been defined for redirection; ensure <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardError" /> is set to <see langword="true" /> and <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> is set to <see langword="false" />.- or - The <see cref="P:System.Diagnostics.Process.StandardError" /> stream has been opened for asynchronous read operations with <see cref="M:System.Diagnostics.Process.BeginErrorReadLine" />. </exception>
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessStandardError")]
- public StreamReader StandardError
- {
- get
- {
- if (this.standardError == null)
- throw new InvalidOperationException(SR.GetString("CantGetStandardError"));
- if (this.errorStreamReadMode == Process.StreamReadMode.undefined)
- this.errorStreamReadMode = Process.StreamReadMode.syncMode;
- else if (this.errorStreamReadMode != Process.StreamReadMode.syncMode)
- throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
- return this.standardError;
- }
- }
- /// <summary>Gets the associated process's physical memory usage, in bytes.</summary>
- /// <returns>The total amount of physical memory the associated process is using, in bytes.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property. </exception>
- [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessWorkingSet")]
- public int WorkingSet
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return (int) this.processInfo.workingSet;
- }
- }
- /// <summary>Gets the amount of physical memory, in bytes, allocated for the associated process.</summary>
- /// <returns>The amount of physical memory, in bytes, allocated for the associated process.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me), which does not support this property.</exception>
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [MonitoringDescription("ProcessWorkingSet")]
- [ComVisible(false)]
- public long WorkingSet64
- {
- get
- {
- this.EnsureState(Process.State.HaveNtProcessInfo);
- return this.processInfo.workingSet;
- }
- }
- /// <summary>Occurs when a process exits.</summary>
- [Category("Behavior")]
- [MonitoringDescription("ProcessExited")]
- public event EventHandler Exited
- {
- add
- {
- this.onExited += value;
- }
- remove
- {
- this.onExited -= value;
- }
- }
- /// <summary>Closes a process that has a user interface by sending a close message to its main window.</summary>
- /// <returns>
- /// <see langword="true" /> if the close message was successfully sent; <see langword="false" /> if the associated process does not have a main window or if the main window is disabled (for example if a modal dialog is being shown).</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">The platform is Windows 98 or Windows Millennium Edition (Windows Me); set the <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property to <see langword="false" /> to access this property on Windows 98 and Windows Me.</exception>
- /// <exception cref="T:System.InvalidOperationException">The process has already exited. -or-No process is associated with this <see cref="T:System.Diagnostics.Process" /> object.</exception>
- public bool CloseMainWindow()
- {
- IntPtr mainWindowHandle = this.MainWindowHandle;
- if (mainWindowHandle == (IntPtr) 0 || (Microsoft.Win32.NativeMethods.GetWindowLong(new HandleRef((object) this, mainWindowHandle), -16) & 134217728) != 0)
- return false;
- Microsoft.Win32.NativeMethods.PostMessage(new HandleRef((object) this, mainWindowHandle), 16, IntPtr.Zero, IntPtr.Zero);
- return true;
- }
- private void ReleaseProcessHandle(SafeProcessHandle handle)
- {
- if (handle == null || this.haveProcessHandle && handle == this.m_processHandle)
- return;
- handle.Close();
- }
- private void CompletionCallback(object context, bool wasSignaled)
- {
- this.StopWatchingForExit();
- this.RaiseOnExited();
- }
- /// <summary>Release all resources used by this process.</summary>
- /// <param name="disposing">
- /// <see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources. </param>
- protected override void Dispose(bool disposing)
- {
- if (this.disposed)
- return;
- if (disposing)
- this.Close();
- this.disposed = true;
- base.Dispose(disposing);
- }
- /// <summary>Frees all the resources that are associated with this component.</summary>
- public void Close()
- {
- if (!this.Associated)
- return;
- if (this.haveProcessHandle)
- {
- this.StopWatchingForExit();
- this.m_processHandle.Close();
- this.m_processHandle = (SafeProcessHandle) null;
- this.haveProcessHandle = false;
- }
- this.haveProcessId = false;
- this.isRemoteMachine = false;
- this.machineName = ".";
- this.raisedOnExited = false;
- this.standardOutput = (StreamReader) null;
- this.standardInput = (StreamWriter) null;
- this.standardError = (StreamReader) null;
- this.output = (AsyncStreamReader) null;
- this.error = (AsyncStreamReader) null;
- this.Refresh();
- }
- private void EnsureState(Process.State state)
- {
- if ((state & Process.State.IsWin2k) != (Process.State) 0 && (this.OperatingSystem.Platform != PlatformID.Win32NT || this.OperatingSystem.Version.Major < 5))
- throw new PlatformNotSupportedException(SR.GetString("Win2kRequired"));
- if ((state & Process.State.IsNt) != (Process.State) 0 && this.OperatingSystem.Platform != PlatformID.Win32NT)
- throw new PlatformNotSupportedException(SR.GetString("WinNTRequired"));
- if ((state & Process.State.Associated) != (Process.State) 0 && !this.Associated)
- throw new InvalidOperationException(SR.GetString("NoAssociatedProcess"));
- if ((state & Process.State.HaveId) != (Process.State) 0 && !this.haveProcessId)
- {
- if (this.haveProcessHandle)
- {
- this.SetProcessId(ProcessManager.GetProcessIdFromHandle(this.m_processHandle));
- }
- else
- {
- this.EnsureState(Process.State.Associated);
- throw new InvalidOperationException(SR.GetString("ProcessIdRequired"));
- }
- }
- if ((state & Process.State.IsLocal) != (Process.State) 0 && this.isRemoteMachine)
- throw new NotSupportedException(SR.GetString("NotSupportedRemote"));
- if ((state & Process.State.HaveProcessInfo) != (Process.State) 0 && this.processInfo == null)
- {
- if ((state & Process.State.HaveId) == (Process.State) 0)
- this.EnsureState(Process.State.HaveId);
- this.processInfo = ProcessManager.GetProcessInfo(this.processId, this.machineName);
- if (this.processInfo == null)
- throw new InvalidOperationException(SR.GetString("NoProcessInfo"));
- }
- if ((state & Process.State.Exited) == (Process.State) 0)
- return;
- if (!this.HasExited)
- throw new InvalidOperationException(SR.GetString("WaitTillExit"));
- if (!this.haveProcessHandle)
- throw new InvalidOperationException(SR.GetString("NoProcessHandle"));
- }
- private void EnsureWatchingForExit()
- {
- if (this.watchingForExit)
- return;
- lock (this)
- {
- if (this.watchingForExit)
- return;
- this.watchingForExit = true;
- try
- {
- this.waitHandle = (WaitHandle) new ProcessWaitHandle(this.m_processHandle);
- this.registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(this.waitHandle, new WaitOrTimerCallback(this.CompletionCallback), (object) null, -1, true);
- }
- catch
- {
- this.watchingForExit = false;
- throw;
- }
- }
- }
- private void EnsureWorkingSetLimits()
- {
- this.EnsureState(Process.State.IsNt);
- if (this.haveWorkingSetLimits)
- return;
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1024);
- IntPtr min;
- IntPtr max;
- if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out min, out max))
- throw new Win32Exception();
- this.minWorkingSet = min;
- this.maxWorkingSet = max;
- this.haveWorkingSetLimits = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- /// <summary>Puts a <see cref="T:System.Diagnostics.Process" /> component in state to interact with operating system processes that run in a special mode by enabling the native property <see langword="SeDebugPrivilege" /> on the current thread.</summary>
- public static void EnterDebugMode()
- {
- if (!ProcessManager.IsNt)
- return;
- Process.SetPrivilege("SeDebugPrivilege", 2);
- }
- private static void SetPrivilege(string privilegeName, int attrib)
- {
- IntPtr TokenHandle = (IntPtr) 0;
- Microsoft.Win32.NativeMethods.LUID lpLuid = new Microsoft.Win32.NativeMethods.LUID();
- if (!Microsoft.Win32.NativeMethods.OpenProcessToken(new HandleRef((object) null, Microsoft.Win32.NativeMethods.GetCurrentProcess()), 32, out TokenHandle))
- throw new Win32Exception();
- try
- {
- if (!Microsoft.Win32.NativeMethods.LookupPrivilegeValue((string) null, privilegeName, out lpLuid))
- throw new Win32Exception();
- Microsoft.Win32.NativeMethods.AdjustTokenPrivileges(new HandleRef((object) null, TokenHandle), false, new Microsoft.Win32.NativeMethods.TokenPrivileges()
- {
- Luid = lpLuid,
- Attributes = attrib
- }, 0, IntPtr.Zero, IntPtr.Zero);
- if (Marshal.GetLastWin32Error() != 0)
- throw new Win32Exception();
- }
- finally
- {
- SafeNativeMethods.CloseHandle(TokenHandle);
- }
- }
- /// <summary>Takes a <see cref="T:System.Diagnostics.Process" /> component out of the state that lets it interact with operating system processes that run in a special mode.</summary>
- public static void LeaveDebugMode()
- {
- if (!ProcessManager.IsNt)
- return;
- Process.SetPrivilege("SeDebugPrivilege", 0);
- }
- /// <summary>Returns a new <see cref="T:System.Diagnostics.Process" /> component, given a process identifier and the name of a computer on the network.</summary>
- /// <param name="processId">The system-unique identifier of a process resource. </param>
- /// <param name="machineName">The name of a computer on the network. </param>
- /// <returns>A <see cref="T:System.Diagnostics.Process" /> component that is associated with a remote process resource identified by the <paramref name="processId" /> parameter.</returns>
- /// <exception cref="T:System.ArgumentException">The process specified by the <paramref name="processId" /> parameter is not running. The identifier might be expired.-or- The <paramref name="machineName" /> parameter syntax is invalid. The name might have length zero (0). </exception>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="machineName" /> parameter is <see langword="null" />. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process was not started by this object.</exception>
- public static Process GetProcessById(int processId, string machineName)
- {
- if (!ProcessManager.IsProcessRunning(processId, machineName))
- throw new ArgumentException(SR.GetString("MissingProccess", (object) processId.ToString((IFormatProvider) CultureInfo.CurrentCulture)));
- return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, (ProcessInfo) null);
- }
- /// <summary>Returns a new <see cref="T:System.Diagnostics.Process" /> component, given the identifier of a process on the local computer.</summary>
- /// <param name="processId">The system-unique identifier of a process resource. </param>
- /// <returns>A <see cref="T:System.Diagnostics.Process" /> component that is associated with the local process resource identified by the <paramref name="processId" /> parameter.</returns>
- /// <exception cref="T:System.ArgumentException">The process specified by the <paramref name="processId" /> parameter is not running. The identifier might be expired. </exception>
- /// <exception cref="T:System.InvalidOperationException">The process was not started by this object.</exception>
- public static Process GetProcessById(int processId)
- {
- return Process.GetProcessById(processId, ".");
- }
- /// <summary>Creates an array of new <see cref="T:System.Diagnostics.Process" /> components and associates them with all the process resources on the local computer that share the specified process name.</summary>
- /// <param name="processName">The friendly name of the process. </param>
- /// <returns>An array of type <see cref="T:System.Diagnostics.Process" /> that represents the process resources running the specified application or file.</returns>
- /// <exception cref="T:System.InvalidOperationException">There are problems accessing the performance counter API's used to get process information. This exception is specific to Windows NT, Windows 2000, and Windows XP. </exception>
- public static Process[] GetProcessesByName(string processName)
- {
- return Process.GetProcessesByName(processName, ".");
- }
- /// <summary>Creates an array of new <see cref="T:System.Diagnostics.Process" /> components and associates them with all the process resources on a remote computer that share the specified process name.</summary>
- /// <param name="processName">The friendly name of the process. </param>
- /// <param name="machineName">The name of a computer on the network. </param>
- /// <returns>An array of type <see cref="T:System.Diagnostics.Process" /> that represents the process resources running the specified application or file.</returns>
- /// <exception cref="T:System.ArgumentException">The <paramref name="machineName" /> parameter syntax is invalid. It might have length zero (0). </exception>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="machineName" /> parameter is <see langword="null" />. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The operating system platform does not support this operation on remote computers. </exception>
- /// <exception cref="T:System.InvalidOperationException">There are problems accessing the performance counter API's used to get process information. This exception is specific to Windows NT, Windows 2000, and Windows XP. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">A problem occurred accessing an underlying system API. </exception>
- public static Process[] GetProcessesByName(string processName, string machineName)
- {
- if (processName == null)
- processName = string.Empty;
- Process[] processes = Process.GetProcesses(machineName);
- ArrayList arrayList = new ArrayList();
- for (int index = 0; index < processes.Length; ++index)
- {
- if (string.Equals(processName, processes[index].ProcessName, StringComparison.OrdinalIgnoreCase))
- arrayList.Add((object) processes[index]);
- else
- processes[index].Dispose();
- }
- Process[] processArray = new Process[arrayList.Count];
- arrayList.CopyTo((Array) processArray, 0);
- return processArray;
- }
- /// <summary>Creates a new <see cref="T:System.Diagnostics.Process" /> component for each process resource on the local computer.</summary>
- /// <returns>An array of type <see cref="T:System.Diagnostics.Process" /> that represents all the process resources running on the local computer.</returns>
- public static Process[] GetProcesses()
- {
- return Process.GetProcesses(".");
- }
- /// <summary>Creates a new <see cref="T:System.Diagnostics.Process" /> component for each process resource on the specified computer.</summary>
- /// <param name="machineName">The computer from which to read the list of processes. </param>
- /// <returns>An array of type <see cref="T:System.Diagnostics.Process" /> that represents all the process resources running on the specified computer.</returns>
- /// <exception cref="T:System.ArgumentException">The <paramref name="machineName" /> parameter syntax is invalid. It might have length zero (0). </exception>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="machineName" /> parameter is <see langword="null" />. </exception>
- /// <exception cref="T:System.PlatformNotSupportedException">The operating system platform does not support this operation on remote computers. </exception>
- /// <exception cref="T:System.InvalidOperationException">There are problems accessing the performance counter API's used to get process information. This exception is specific to Windows NT, Windows 2000, and Windows XP. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">A problem occurred accessing an underlying system API. </exception>
- public static Process[] GetProcesses(string machineName)
- {
- bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
- ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
- Process[] processArray = new Process[processInfos.Length];
- for (int index = 0; index < processInfos.Length; ++index)
- {
- ProcessInfo processInfo = processInfos[index];
- processArray[index] = new Process(machineName, isRemoteMachine, processInfo.processId, processInfo);
- }
- return processArray;
- }
- /// <summary>Gets a new <see cref="T:System.Diagnostics.Process" /> component and associates it with the currently active process.</summary>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> component associated with the process resource that is running the calling application.</returns>
- public static Process GetCurrentProcess()
- {
- return new Process(".", false, Microsoft.Win32.NativeMethods.GetCurrentProcessId(), (ProcessInfo) null);
- }
- /// <summary>Raises the <see cref="E:System.Diagnostics.Process.Exited" /> event.</summary>
- protected void OnExited()
- {
- EventHandler onExited = this.onExited;
- if (onExited == null)
- return;
- if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
- this.SynchronizingObject.BeginInvoke((Delegate) onExited, new object[2]
- {
- (object) this,
- (object) EventArgs.Empty
- });
- else
- onExited((object) this, EventArgs.Empty);
- }
- private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited)
- {
- if (this.haveProcessHandle)
- {
- if (throwIfExited)
- {
- ProcessWaitHandle processWaitHandle = (ProcessWaitHandle) null;
- try
- {
- processWaitHandle = new ProcessWaitHandle(this.m_processHandle);
- if (processWaitHandle.WaitOne(0, false))
- {
- if (this.haveProcessId)
- throw new InvalidOperationException(SR.GetString("ProcessHasExited", (object) this.processId.ToString((IFormatProvider) CultureInfo.CurrentCulture)));
- throw new InvalidOperationException(SR.GetString("ProcessHasExitedNoId"));
- }
- }
- finally
- {
- processWaitHandle?.Close();
- }
- }
- return this.m_processHandle;
- }
- this.EnsureState(Process.State.HaveId | Process.State.IsLocal);
- SafeProcessHandle invalidHandle = SafeProcessHandle.InvalidHandle;
- SafeProcessHandle processHandle = ProcessManager.OpenProcess(this.processId, access, throwIfExited);
- if (throwIfExited && (access & 1024) != 0 && (Microsoft.Win32.NativeMethods.GetExitCodeProcess(processHandle, out this.exitCode) && this.exitCode != 259))
- throw new InvalidOperationException(SR.GetString("ProcessHasExited", (object) this.processId.ToString((IFormatProvider) CultureInfo.CurrentCulture)));
- return processHandle;
- }
- private SafeProcessHandle GetProcessHandle(int access)
- {
- return this.GetProcessHandle(access, true);
- }
- private SafeProcessHandle OpenProcessHandle()
- {
- return this.OpenProcessHandle(2035711);
- }
- private SafeProcessHandle OpenProcessHandle(int access)
- {
- if (!this.haveProcessHandle)
- {
- if (this.disposed)
- throw new ObjectDisposedException(this.GetType().Name);
- this.SetProcessHandle(this.GetProcessHandle(access));
- }
- return this.m_processHandle;
- }
- private void RaiseOnExited()
- {
- if (this.raisedOnExited)
- return;
- lock (this)
- {
- if (this.raisedOnExited)
- return;
- this.raisedOnExited = true;
- this.OnExited();
- }
- }
- /// <summary>Discards any information about the associated process that has been cached inside the process component.</summary>
- public void Refresh()
- {
- this.processInfo = (ProcessInfo) null;
- this.threads = (ProcessThreadCollection) null;
- this.modules = (ProcessModuleCollection) null;
- this.mainWindowTitle = (string) null;
- this.exited = false;
- this.signaled = false;
- this.haveMainWindow = false;
- this.haveWorkingSetLimits = false;
- this.haveProcessorAffinity = false;
- this.havePriorityClass = false;
- this.haveExitTime = false;
- this.haveResponding = false;
- this.havePriorityBoostEnabled = false;
- }
- private void SetProcessHandle(SafeProcessHandle processHandle)
- {
- this.m_processHandle = processHandle;
- this.haveProcessHandle = true;
- if (!this.watchForExit)
- return;
- this.EnsureWatchingForExit();
- }
- private void SetProcessId(int processId)
- {
- this.processId = processId;
- this.haveProcessId = true;
- }
- private void SetWorkingSetLimits(object newMin, object newMax)
- {
- this.EnsureState(Process.State.IsNt);
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1280);
- IntPtr min;
- IntPtr max;
- if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out min, out max))
- throw new Win32Exception();
- if (newMin != null)
- min = (IntPtr) newMin;
- if (newMax != null)
- max = (IntPtr) newMax;
- if ((long) min > (long) max)
- {
- if (newMin != null)
- throw new ArgumentException(SR.GetString("BadMinWorkset"));
- throw new ArgumentException(SR.GetString("BadMaxWorkset"));
- }
- if (!Microsoft.Win32.NativeMethods.SetProcessWorkingSetSize(handle, min, max))
- throw new Win32Exception();
- if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out min, out max))
- throw new Win32Exception();
- this.minWorkingSet = min;
- this.maxWorkingSet = max;
- this.haveWorkingSetLimits = true;
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- /// <summary>Starts (or reuses) the process resource that is specified by the <see cref="P:System.Diagnostics.Process.StartInfo" /> property of this <see cref="T:System.Diagnostics.Process" /> component and associates it with the component.</summary>
- /// <returns>
- /// <see langword="true" /> if a process resource is started; <see langword="false" /> if no new process resource is started (for example, if an existing process is reused).</returns>
- /// <exception cref="T:System.InvalidOperationException">No file name was specified in the <see cref="T:System.Diagnostics.Process" /> component's <see cref="P:System.Diagnostics.Process.StartInfo" />.-or- The <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> member of the <see cref="P:System.Diagnostics.Process.StartInfo" /> property is <see langword="true" /> while <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardInput" />, <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardOutput" />, or <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardError" /> is <see langword="true" />. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">There was an error in opening the associated file. </exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- public bool Start()
- {
- this.Close();
- ProcessStartInfo startInfo = this.StartInfo;
- if (startInfo.FileName.Length == 0)
- throw new InvalidOperationException(SR.GetString("FileNameMissing"));
- if (startInfo.UseShellExecute)
- return this.StartWithShellExecuteEx(startInfo);
- return this.StartWithCreateProcess(startInfo);
- }
- private static void CreatePipeWithSecurityAttributes(
- out SafeFileHandle hReadPipe,
- out SafeFileHandle hWritePipe,
- Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES lpPipeAttributes,
- int nSize)
- {
- if (!Microsoft.Win32.NativeMethods.CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize) || hReadPipe.IsInvalid || hWritePipe.IsInvalid)
- throw new Win32Exception();
- }
- private void CreatePipe(
- out SafeFileHandle parentHandle,
- out SafeFileHandle childHandle,
- bool parentInputs)
- {
- Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES lpPipeAttributes = new Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES();
- lpPipeAttributes.bInheritHandle = true;
- SafeFileHandle safeFileHandle = (SafeFileHandle) null;
- try
- {
- if (parentInputs)
- Process.CreatePipeWithSecurityAttributes(out childHandle, out safeFileHandle, lpPipeAttributes, 0);
- else
- Process.CreatePipeWithSecurityAttributes(out safeFileHandle, out childHandle, lpPipeAttributes, 0);
- if (!Microsoft.Win32.NativeMethods.DuplicateHandle(new HandleRef((object) this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), (System.Runtime.InteropServices.SafeHandle) safeFileHandle, new HandleRef((object) this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), out parentHandle, 0, false, 2))
- throw new Win32Exception();
- }
- finally
- {
- if (safeFileHandle != null && !safeFileHandle.IsInvalid)
- safeFileHandle.Close();
- }
- }
- private static StringBuilder BuildCommandLine(
- string executableFileName,
- string arguments)
- {
- StringBuilder stringBuilder = new StringBuilder();
- string str = executableFileName.Trim();
- bool flag = str.StartsWith("\"", StringComparison.Ordinal) && str.EndsWith("\"", StringComparison.Ordinal);
- if (!flag)
- stringBuilder.Append("\"");
- stringBuilder.Append(str);
- if (!flag)
- stringBuilder.Append("\"");
- if (!string.IsNullOrEmpty(arguments))
- {
- stringBuilder.Append(" ");
- stringBuilder.Append(arguments);
- }
- return stringBuilder;
- }
- private bool StartWithCreateProcess(ProcessStartInfo startInfo)
- {
- if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
- throw new InvalidOperationException(SR.GetString("StandardOutputEncodingNotAllowed"));
- if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
- throw new InvalidOperationException(SR.GetString("StandardErrorEncodingNotAllowed"));
- if (this.disposed)
- throw new ObjectDisposedException(this.GetType().Name);
- StringBuilder stringBuilder = Process.BuildCommandLine(startInfo.FileName, startInfo.Arguments);
- Microsoft.Win32.NativeMethods.STARTUPINFO lpStartupInfo = new Microsoft.Win32.NativeMethods.STARTUPINFO();
- SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new SafeNativeMethods.PROCESS_INFORMATION();
- SafeProcessHandle processHandle = new SafeProcessHandle();
- SafeThreadHandle safeThreadHandle = new SafeThreadHandle();
- int error = 0;
- SafeFileHandle parentHandle1 = (SafeFileHandle) null;
- SafeFileHandle parentHandle2 = (SafeFileHandle) null;
- SafeFileHandle parentHandle3 = (SafeFileHandle) null;
- GCHandle gcHandle = new GCHandle();
- lock (Process.s_CreateProcessLock)
- {
- try
- {
- if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
- {
- if (startInfo.RedirectStandardInput)
- this.CreatePipe(out parentHandle1, out lpStartupInfo.hStdInput, true);
- else
- lpStartupInfo.hStdInput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-10), false);
- if (startInfo.RedirectStandardOutput)
- this.CreatePipe(out parentHandle2, out lpStartupInfo.hStdOutput, false);
- else
- lpStartupInfo.hStdOutput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-11), false);
- if (startInfo.RedirectStandardError)
- this.CreatePipe(out parentHandle3, out lpStartupInfo.hStdError, false);
- else
- lpStartupInfo.hStdError = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-12), false);
- lpStartupInfo.dwFlags = 256;
- }
- int num1 = 0;
- if (startInfo.CreateNoWindow)
- num1 |= 134217728;
- IntPtr num2 = (IntPtr) 0;
- if (startInfo.environmentVariables != null)
- {
- bool unicode = false;
- if (ProcessManager.IsNt)
- {
- num1 |= 1024;
- unicode = true;
- }
- gcHandle = GCHandle.Alloc((object) EnvironmentBlock.ToByteArray(startInfo.environmentVariables, unicode), GCHandleType.Pinned);
- num2 = gcHandle.AddrOfPinnedObject();
- }
- string lpCurrentDirectory = startInfo.WorkingDirectory;
- if (lpCurrentDirectory == string.Empty)
- lpCurrentDirectory = Environment.CurrentDirectory;
- if (startInfo.UserName.Length != 0)
- {
- if (startInfo.Password != null && startInfo.PasswordInClearText != null)
- throw new ArgumentException(SR.GetString("CantSetDuplicatePassword"));
- Microsoft.Win32.NativeMethods.LogonFlags logonFlags = (Microsoft.Win32.NativeMethods.LogonFlags) 0;
- if (startInfo.LoadUserProfile)
- logonFlags = Microsoft.Win32.NativeMethods.LogonFlags.LOGON_WITH_PROFILE;
- IntPtr num3 = IntPtr.Zero;
- try
- {
- num3 = startInfo.Password == null ? (startInfo.PasswordInClearText == null ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.StringToCoTaskMemUni(startInfo.PasswordInClearText)) : Marshal.SecureStringToCoTaskMemUnicode(startInfo.Password);
- RuntimeHelpers.PrepareConstrainedRegions();
- bool processWithLogonW;
- try
- {
- }
- finally
- {
- processWithLogonW = Microsoft.Win32.NativeMethods.CreateProcessWithLogonW(startInfo.UserName, startInfo.Domain, num3, logonFlags, (string) null, stringBuilder, num1, num2, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
- if (!processWithLogonW)
- error = Marshal.GetLastWin32Error();
- if (lpProcessInformation.hProcess != (IntPtr) 0 && lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
- processHandle.InitialSetHandle(lpProcessInformation.hProcess);
- if (lpProcessInformation.hThread != (IntPtr) 0 && lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
- safeThreadHandle.InitialSetHandle(lpProcessInformation.hThread);
- }
- if (!processWithLogonW)
- {
- if (error == 193 || error == 216)
- throw new Win32Exception(error, SR.GetString("InvalidApplication"));
- throw new Win32Exception(error);
- }
- }
- finally
- {
- if (num3 != IntPtr.Zero)
- Marshal.ZeroFreeCoTaskMemUnicode(num3);
- }
- }
- else
- {
- RuntimeHelpers.PrepareConstrainedRegions();
- bool process;
- try
- {
- }
- finally
- {
- process = Microsoft.Win32.NativeMethods.CreateProcess((string) null, stringBuilder, (Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES) null, (Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES) null, true, num1, num2, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
- if (!process)
- error = Marshal.GetLastWin32Error();
- if (lpProcessInformation.hProcess != (IntPtr) 0 && lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
- processHandle.InitialSetHandle(lpProcessInformation.hProcess);
- if (lpProcessInformation.hThread != (IntPtr) 0 && lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
- safeThreadHandle.InitialSetHandle(lpProcessInformation.hThread);
- }
- if (!process)
- {
- if (error == 193 || error == 216)
- throw new Win32Exception(error, SR.GetString("InvalidApplication"));
- throw new Win32Exception(error);
- }
- }
- }
- finally
- {
- if (gcHandle.IsAllocated)
- gcHandle.Free();
- lpStartupInfo.Dispose();
- }
- }
- if (startInfo.RedirectStandardInput)
- {
- this.standardInput = new StreamWriter((Stream) new FileStream(parentHandle1, FileAccess.Write, 4096, false), Console.InputEncoding, 4096);
- this.standardInput.AutoFlush = true;
- }
- if (startInfo.RedirectStandardOutput)
- {
- Encoding encoding = startInfo.StandardOutputEncoding != null ? startInfo.StandardOutputEncoding : Console.OutputEncoding;
- this.standardOutput = new StreamReader((Stream) new FileStream(parentHandle2, FileAccess.Read, 4096, false), encoding, true, 4096);
- }
- if (startInfo.RedirectStandardError)
- {
- Encoding encoding = startInfo.StandardErrorEncoding != null ? startInfo.StandardErrorEncoding : Console.OutputEncoding;
- this.standardError = new StreamReader((Stream) new FileStream(parentHandle3, FileAccess.Read, 4096, false), encoding, true, 4096);
- }
- bool flag = false;
- if (!processHandle.IsInvalid)
- {
- this.SetProcessHandle(processHandle);
- this.SetProcessId(lpProcessInformation.dwProcessId);
- safeThreadHandle.Close();
- flag = true;
- }
- return flag;
- }
- private bool StartWithShellExecuteEx(ProcessStartInfo startInfo)
- {
- if (this.disposed)
- throw new ObjectDisposedException(this.GetType().Name);
- if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null)
- throw new InvalidOperationException(SR.GetString("CantStartAsUser"));
- if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
- throw new InvalidOperationException(SR.GetString("CantRedirectStreams"));
- if (startInfo.StandardErrorEncoding != null)
- throw new InvalidOperationException(SR.GetString("StandardErrorEncodingNotAllowed"));
- if (startInfo.StandardOutputEncoding != null)
- throw new InvalidOperationException(SR.GetString("StandardOutputEncodingNotAllowed"));
- if (startInfo.environmentVariables != null)
- throw new InvalidOperationException(SR.GetString("CantUseEnvVars"));
- Microsoft.Win32.NativeMethods.ShellExecuteInfo executeInfo = new Microsoft.Win32.NativeMethods.ShellExecuteInfo();
- executeInfo.fMask = 64;
- if (startInfo.ErrorDialog)
- executeInfo.hwnd = startInfo.ErrorDialogParentHandle;
- else
- executeInfo.fMask |= 1024;
- switch (startInfo.WindowStyle)
- {
- case ProcessWindowStyle.Hidden:
- executeInfo.nShow = 0;
- break;
- case ProcessWindowStyle.Minimized:
- executeInfo.nShow = 2;
- break;
- case ProcessWindowStyle.Maximized:
- executeInfo.nShow = 3;
- break;
- default:
- executeInfo.nShow = 1;
- break;
- }
- try
- {
- if (startInfo.FileName.Length != 0)
- executeInfo.lpFile = Marshal.StringToHGlobalAuto(startInfo.FileName);
- if (startInfo.Verb.Length != 0)
- executeInfo.lpVerb = Marshal.StringToHGlobalAuto(startInfo.Verb);
- if (startInfo.Arguments.Length != 0)
- executeInfo.lpParameters = Marshal.StringToHGlobalAuto(startInfo.Arguments);
- if (startInfo.WorkingDirectory.Length != 0)
- executeInfo.lpDirectory = Marshal.StringToHGlobalAuto(startInfo.WorkingDirectory);
- executeInfo.fMask |= 256;
- ShellExecuteHelper shellExecuteHelper = new ShellExecuteHelper(executeInfo);
- if (!shellExecuteHelper.ShellExecuteOnSTAThread())
- {
- int error = shellExecuteHelper.ErrorCode;
- if (error == 0)
- {
- long hInstApp = (long) executeInfo.hInstApp;
- switch (hInstApp - 2L)
- {
- case 0:
- error = 2;
- break;
- case 1:
- error = 3;
- break;
- case 2:
- case 4:
- case 5:
- label_41:
- error = (int) executeInfo.hInstApp;
- break;
- case 3:
- error = 5;
- break;
- case 6:
- error = 8;
- break;
- default:
- switch (hInstApp - 26L)
- {
- case 0:
- error = 32;
- break;
- case 2:
- case 3:
- case 4:
- error = 1156;
- break;
- case 5:
- error = 1155;
- break;
- case 6:
- error = 1157;
- break;
- default:
- goto label_41;
- }
- }
- }
- if (error == 193 || error == 216)
- throw new Win32Exception(error, SR.GetString("InvalidApplication"));
- throw new Win32Exception(error);
- }
- }
- finally
- {
- if (executeInfo.lpFile != (IntPtr) 0)
- Marshal.FreeHGlobal(executeInfo.lpFile);
- if (executeInfo.lpVerb != (IntPtr) 0)
- Marshal.FreeHGlobal(executeInfo.lpVerb);
- if (executeInfo.lpParameters != (IntPtr) 0)
- Marshal.FreeHGlobal(executeInfo.lpParameters);
- if (executeInfo.lpDirectory != (IntPtr) 0)
- Marshal.FreeHGlobal(executeInfo.lpDirectory);
- }
- if (!(executeInfo.hProcess != (IntPtr) 0))
- return false;
- this.SetProcessHandle(new SafeProcessHandle(executeInfo.hProcess));
- return true;
- }
- /// <summary>Starts a process resource by specifying the name of an application, a user name, a password, and a domain and associates the resource with a new <see cref="T:System.Diagnostics.Process" /> component.</summary>
- /// <param name="fileName">The name of an application file to run in the process.</param>
- /// <param name="userName">The user name to use when starting the process.</param>
- /// <param name="password">A <see cref="T:System.Security.SecureString" /> that contains the password to use when starting the process.</param>
- /// <param name="domain">The domain to use when starting the process.</param>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> that is associated with the process resource, or <see langword="null" /> if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its <see cref="P:System.Diagnostics.Process.HasExited" /> property already set to <see langword="true" />. In this case, the started process may have activated an existing instance of itself and then exited.</returns>
- /// <exception cref="T:System.InvalidOperationException">No file name was specified. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// <paramref name="fileName" /> is not an executable (.exe) file.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">There was an error in opening the associated file. </exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- public static Process Start(
- string fileName,
- string userName,
- SecureString password,
- string domain)
- {
- return Process.Start(new ProcessStartInfo(fileName)
- {
- UserName = userName,
- Password = password,
- Domain = domain,
- UseShellExecute = false
- });
- }
- /// <summary>Starts a process resource by specifying the name of an application, a set of command-line arguments, a user name, a password, and a domain and associates the resource with a new <see cref="T:System.Diagnostics.Process" /> component.</summary>
- /// <param name="fileName">The name of an application file to run in the process. </param>
- /// <param name="arguments">Command-line arguments to pass when starting the process. </param>
- /// <param name="userName">The user name to use when starting the process.</param>
- /// <param name="password">A <see cref="T:System.Security.SecureString" /> that contains the password to use when starting the process.</param>
- /// <param name="domain">The domain to use when starting the process.</param>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> that is associated with the process resource, or <see langword="null" /> if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its <see cref="P:System.Diagnostics.Process.HasExited" /> property already set to <see langword="true" />. In this case, the started process may have activated an existing instance of itself and then exited.</returns>
- /// <exception cref="T:System.InvalidOperationException">No file name was specified.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// <paramref name="fileName" /> is not an executable (.exe) file.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">An error occurred when opening the associated file. -or-The sum of the length of the arguments and the length of the full path to the associated file exceeds 2080. The error message associated with this exception can be one of the following: "The data area passed to a system call is too small." or "Access is denied."</exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- public static Process Start(
- string fileName,
- string arguments,
- string userName,
- SecureString password,
- string domain)
- {
- return Process.Start(new ProcessStartInfo(fileName, arguments)
- {
- UserName = userName,
- Password = password,
- Domain = domain,
- UseShellExecute = false
- });
- }
- /// <summary>Starts a process resource by specifying the name of a document or application file and associates the resource with a new <see cref="T:System.Diagnostics.Process" /> component.</summary>
- /// <param name="fileName">The name of a document or application file to run in the process. </param>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> that is associated with the process resource, or <see langword="null" /> if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its <see cref="P:System.Diagnostics.Process.HasExited" /> property already set to <see langword="true" />. In this case, the started process may have activated an existing instance of itself and then exited.</returns>
- /// <exception cref="T:System.ComponentModel.Win32Exception">An error occurred when opening the associated file. </exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- /// <exception cref="T:System.IO.FileNotFoundException">The PATH environment variable has a string containing quotes.</exception>
- public static Process Start(string fileName)
- {
- return Process.Start(new ProcessStartInfo(fileName));
- }
- /// <summary>Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new <see cref="T:System.Diagnostics.Process" /> component.</summary>
- /// <param name="fileName">The name of an application file to run in the process. </param>
- /// <param name="arguments">Command-line arguments to pass when starting the process. </param>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> that is associated with the process resource, or <see langword="null" /> if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its <see cref="P:System.Diagnostics.Process.HasExited" /> property already set to <see langword="true" />. In this case, the started process may have activated an existing instance of itself and then exited.</returns>
- /// <exception cref="T:System.InvalidOperationException">The <paramref name="fileName" /> or <paramref name="arguments" /> parameter is <see langword="null" />. </exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">An error occurred when opening the associated file. -or-The sum of the length of the arguments and the length of the full path to the process exceeds 2080. The error message associated with this exception can be one of the following: "The data area passed to a system call is too small." or "Access is denied."</exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- /// <exception cref="T:System.IO.FileNotFoundException">The PATH environment variable has a string containing quotes.</exception>
- public static Process Start(string fileName, string arguments)
- {
- return Process.Start(new ProcessStartInfo(fileName, arguments));
- }
- /// <summary>Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new <see cref="T:System.Diagnostics.Process" /> component.</summary>
- /// <param name="startInfo">The <see cref="T:System.Diagnostics.ProcessStartInfo" /> that contains the information that is used to start the process, including the file name and any command-line arguments. </param>
- /// <returns>A new <see cref="T:System.Diagnostics.Process" /> that is associated with the process resource, or <see langword="null" /> if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its <see cref="P:System.Diagnostics.Process.HasExited" /> property already set to <see langword="true" />. In this case, the started process may have activated an existing instance of itself and then exited.</returns>
- /// <exception cref="T:System.InvalidOperationException">No file name was specified in the <paramref name="startInfo" /> parameter's <see cref="P:System.Diagnostics.ProcessStartInfo.FileName" /> property.-or- The <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property of the <paramref name="startInfo" /> parameter is <see langword="true" /> and the <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardInput" />, <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardOutput" />, or <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardError" /> property is also <see langword="true" />.-or-The <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> property of the <paramref name="startInfo" /> parameter is <see langword="true" /> and the <see cref="P:System.Diagnostics.ProcessStartInfo.UserName" /> property is not <see langword="null" /> or empty or the <see cref="P:System.Diagnostics.ProcessStartInfo.Password" /> property is not <see langword="null" />.</exception>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="startInfo" /> parameter is <see langword="null" />. </exception>
- /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception>
- /// <exception cref="T:System.IO.FileNotFoundException">The file specified in the <paramref name="startInfo" /> parameter's <see cref="P:System.Diagnostics.ProcessStartInfo.FileName" /> property could not be found.</exception>
- /// <exception cref="T:System.ComponentModel.Win32Exception">An error occurred when opening the associated file. -or-The sum of the length of the arguments and the length of the full path to the process exceeds 2080. The error message associated with this exception can be one of the following: "The data area passed to a system call is too small." or "Access is denied."</exception>
- public static Process Start(ProcessStartInfo startInfo)
- {
- Process process = new Process();
- if (startInfo == null)
- throw new ArgumentNullException(nameof (startInfo));
- process.StartInfo = startInfo;
- if (process.Start())
- return process;
- return (Process) null;
- }
- /// <summary>Immediately stops the associated process.</summary>
- /// <exception cref="T:System.ComponentModel.Win32Exception">The associated process could not be terminated. -or-The process is terminating.-or- The associated process is a Win16 executable.</exception>
- /// <exception cref="T:System.NotSupportedException">You are attempting to call <see cref="M:System.Diagnostics.Process.Kill" /> for a process that is running on a remote computer. The method is available only for processes running on the local computer.</exception>
- /// <exception cref="T:System.InvalidOperationException">The process has already exited. -or-There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object.</exception>
- public void Kill()
- {
- SafeProcessHandle safeProcessHandle = (SafeProcessHandle) null;
- try
- {
- safeProcessHandle = this.GetProcessHandle(1);
- if (!Microsoft.Win32.NativeMethods.TerminateProcess(safeProcessHandle, -1))
- throw new Win32Exception();
- }
- finally
- {
- this.ReleaseProcessHandle(safeProcessHandle);
- }
- }
- private void StopWatchingForExit()
- {
- if (!this.watchingForExit)
- return;
- lock (this)
- {
- if (!this.watchingForExit)
- return;
- this.watchingForExit = false;
- this.registeredWaitHandle.Unregister((WaitHandle) null);
- this.waitHandle.Close();
- this.waitHandle = (WaitHandle) null;
- this.registeredWaitHandle = (RegisteredWaitHandle) null;
- }
- }
- /// <summary>Formats the process's name as a string, combined with the parent component type, if applicable.</summary>
- /// <returns>The <see cref="P:System.Diagnostics.Process.ProcessName" />, combined with the base component's <see cref="M:System.Object.ToString" /> return value.</returns>
- /// <exception cref="T:System.PlatformNotSupportedException">
- /// <see cref="M:System.Diagnostics.Process.ToString" /> is not supported on Windows 98.</exception>
- public override string ToString()
- {
- if (!this.Associated)
- return base.ToString();
- string str = string.Empty;
- try
- {
- str = this.ProcessName;
- }
- catch (PlatformNotSupportedException ex)
- {
- }
- if (str.Length == 0)
- return base.ToString();
- return string.Format((IFormatProvider) CultureInfo.CurrentCulture, "{0} ({1})", new object[2]
- {
- (object) base.ToString(),
- (object) str
- });
- }
- /// <summary>Instructs the <see cref="T:System.Diagnostics.Process" /> component to wait the specified number of milliseconds for the associated process to exit.</summary>
- /// <param name="milliseconds">The amount of time, in milliseconds, to wait for the associated process to exit. The maximum is the largest possible value of a 32-bit integer, which represents infinity to the operating system. </param>
- /// <returns>
- /// <see langword="true" /> if the associated process has exited; otherwise, <see langword="false" />.</returns>
- /// <exception cref="T:System.ComponentModel.Win32Exception">The wait setting could not be accessed. </exception>
- /// <exception cref="T:System.SystemException">No process <see cref="P:System.Diagnostics.Process.Id" /> has been set, and a <see cref="P:System.Diagnostics.Process.Handle" /> from which the <see cref="P:System.Diagnostics.Process.Id" /> property can be determined does not exist.-or- There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object.-or- You are attempting to call <see cref="M:System.Diagnostics.Process.WaitForExit(System.Int32)" /> for a process that is running on a remote computer. This method is available only for processes that are running on the local computer. </exception>
- public bool WaitForExit(int milliseconds)
- {
- SafeProcessHandle safeProcessHandle = (SafeProcessHandle) null;
- ProcessWaitHandle processWaitHandle = (ProcessWaitHandle) null;
- bool flag;
- try
- {
- safeProcessHandle = this.GetProcessHandle(1048576, false);
- if (safeProcessHandle.IsInvalid)
- {
- flag = true;
- }
- else
- {
- processWaitHandle = new ProcessWaitHandle(safeProcessHandle);
- if (processWaitHandle.WaitOne(milliseconds, false))
- {
- flag = true;
- this.signaled = true;
- }
- else
- {
- flag = false;
- this.signaled = false;
- }
- }
- }
- finally
- {
- processWaitHandle?.Close();
- if (this.output != null && milliseconds == -1)
- this.output.WaitUtilEOF();
- if (this.error != null && milliseconds == -1)
- this.error.WaitUtilEOF();
- this.ReleaseProcessHandle(safeProcessHandle);
- }
- if (flag && this.watchForExit)
- this.RaiseOnExited();
- return flag;
- }
- /// <summary>Instructs the <see cref="T:System.Diagnostics.Process" /> component to wait indefinitely for the associated process to exit.</summary>
- /// <exception cref="T:System.ComponentModel.Win32Exception">The wait setting could not be accessed. </exception>
- /// <exception cref="T:System.SystemException">No process <see cref="P:System.Diagnostics.Process.Id" /> has been set, and a <see cref="P:System.Diagnostics.Process.Handle" /> from which the <see cref="P:System.Diagnostics.Process.Id" /> property can be determined does not exist.-or- There is no process associated with this <see cref="T:System.Diagnostics.Process" /> object.-or- You are attempting to call <see cref="M:System.Diagnostics.Process.WaitForExit" /> for a process that is running on a remote computer. This method is available only for processes that are running on the local computer. </exception>
- public void WaitForExit()
- {
- this.WaitForExit(-1);
- }
- /// <summary>Causes the <see cref="T:System.Diagnostics.Process" /> component to wait the specified number of milliseconds for the associated process to enter an idle state. This overload applies only to processes with a user interface and, therefore, a message loop.</summary>
- /// <param name="milliseconds">A value of 1 to <see cref="F:System.Int32.MaxValue" /> that specifies the amount of time, in milliseconds, to wait for the associated process to become idle. A value of 0 specifies an immediate return, and a value of -1 specifies an infinite wait. </param>
- /// <returns>
- /// <see langword="true" /> if the associated process has reached an idle state; otherwise, <see langword="false" />.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process does not have a graphical interface.-or-An unknown error occurred. The process failed to enter an idle state.-or-The process has already exited. -or-No process is associated with this <see cref="T:System.Diagnostics.Process" /> object.</exception>
- public bool WaitForInputIdle(int milliseconds)
- {
- SafeProcessHandle handle = (SafeProcessHandle) null;
- try
- {
- handle = this.GetProcessHandle(1049600);
- switch (Microsoft.Win32.NativeMethods.WaitForInputIdle(handle, milliseconds))
- {
- case 0:
- return true;
- case 258:
- return false;
- default:
- throw new InvalidOperationException(SR.GetString("InputIdleUnkownError"));
- }
- }
- finally
- {
- this.ReleaseProcessHandle(handle);
- }
- }
- /// <summary>Causes the <see cref="T:System.Diagnostics.Process" /> component to wait indefinitely for the associated process to enter an idle state. This overload applies only to processes with a user interface and, therefore, a message loop.</summary>
- /// <returns>
- /// <see langword="true" /> if the associated process has reached an idle state.</returns>
- /// <exception cref="T:System.InvalidOperationException">The process does not have a graphical interface.-or-An unknown error occurred. The process failed to enter an idle state.-or-The process has already exited. -or-No process is associated with this <see cref="T:System.Diagnostics.Process" /> object.</exception>
- public bool WaitForInputIdle()
- {
- return this.WaitForInputIdle(int.MaxValue);
- }
- /// <summary>Begins asynchronous read operations on the redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream of the application.</summary>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardOutput" /> property is <see langword="false" />.- or - An asynchronous read operation is already in progress on the <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream.- or - The <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream has been used by a synchronous read operation. </exception>
- [ComVisible(false)]
- public void BeginOutputReadLine()
- {
- if (this.outputStreamReadMode == Process.StreamReadMode.undefined)
- this.outputStreamReadMode = Process.StreamReadMode.asyncMode;
- else if (this.outputStreamReadMode != Process.StreamReadMode.asyncMode)
- throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
- if (this.pendingOutputRead)
- throw new InvalidOperationException(SR.GetString("PendingAsyncOperation"));
- this.pendingOutputRead = true;
- if (this.output == null)
- {
- if (this.standardOutput == null)
- throw new InvalidOperationException(SR.GetString("CantGetStandardOut"));
- this.output = new AsyncStreamReader(this, this.standardOutput.BaseStream, new UserCallBack(this.OutputReadNotifyUser), this.standardOutput.CurrentEncoding);
- }
- this.output.BeginReadLine();
- }
- /// <summary>Begins asynchronous read operations on the redirected <see cref="P:System.Diagnostics.Process.StandardError" /> stream of the application.</summary>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardError" /> property is <see langword="false" />.- or - An asynchronous read operation is already in progress on the <see cref="P:System.Diagnostics.Process.StandardError" /> stream.- or - The <see cref="P:System.Diagnostics.Process.StandardError" /> stream has been used by a synchronous read operation. </exception>
- [ComVisible(false)]
- public void BeginErrorReadLine()
- {
- if (this.errorStreamReadMode == Process.StreamReadMode.undefined)
- this.errorStreamReadMode = Process.StreamReadMode.asyncMode;
- else if (this.errorStreamReadMode != Process.StreamReadMode.asyncMode)
- throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
- if (this.pendingErrorRead)
- throw new InvalidOperationException(SR.GetString("PendingAsyncOperation"));
- this.pendingErrorRead = true;
- if (this.error == null)
- {
- if (this.standardError == null)
- throw new InvalidOperationException(SR.GetString("CantGetStandardError"));
- this.error = new AsyncStreamReader(this, this.standardError.BaseStream, new UserCallBack(this.ErrorReadNotifyUser), this.standardError.CurrentEncoding);
- }
- this.error.BeginReadLine();
- }
- /// <summary>Cancels the asynchronous read operation on the redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream of an application.</summary>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.StandardOutput" /> stream is not enabled for asynchronous read operations. </exception>
- [ComVisible(false)]
- public void CancelOutputRead()
- {
- if (this.output == null)
- throw new InvalidOperationException(SR.GetString("NoAsyncOperation"));
- this.output.CancelOperation();
- this.pendingOutputRead = false;
- }
- /// <summary>Cancels the asynchronous read operation on the redirected <see cref="P:System.Diagnostics.Process.StandardError" /> stream of an application.</summary>
- /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Diagnostics.Process.StandardError" /> stream is not enabled for asynchronous read operations. </exception>
- [ComVisible(false)]
- public void CancelErrorRead()
- {
- if (this.error == null)
- throw new InvalidOperationException(SR.GetString("NoAsyncOperation"));
- this.error.CancelOperation();
- this.pendingErrorRead = false;
- }
- internal void OutputReadNotifyUser(string data)
- {
- DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
- if (outputDataReceived == null)
- return;
- DataReceivedEventArgs e = new DataReceivedEventArgs(data);
- if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
- this.SynchronizingObject.Invoke((Delegate) outputDataReceived, new object[2]
- {
- (object) this,
- (object) e
- });
- else
- outputDataReceived((object) this, e);
- }
- internal void ErrorReadNotifyUser(string data)
- {
- DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
- if (errorDataReceived == null)
- return;
- DataReceivedEventArgs e = new DataReceivedEventArgs(data);
- if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
- this.SynchronizingObject.Invoke((Delegate) errorDataReceived, new object[2]
- {
- (object) this,
- (object) e
- });
- else
- errorDataReceived((object) this, e);
- }
- private enum StreamReadMode
- {
- undefined,
- syncMode,
- asyncMode,
- }
- private enum State
- {
- HaveId = 1,
- IsLocal = 2,
- IsNt = 4,
- HaveProcessInfo = 8,
- HaveNtProcessInfo = 12, // 0x0000000C
- Exited = 16, // 0x00000010
- Associated = 32, // 0x00000020
- IsWin2k = 64, // 0x00000040
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement