C launch process windows

Launching processes from a Windows Service

I have written a C# Windows Service (for use on Windows 8.1 (32/64 bit) and Windows 10) that monitors for certain conditions and when these are met, it launches another Windows Forms application with some arguments that control a message displayed to a user. I’m well aware of the issues of a service interacting with a user session, and the service uses a (slightly) modified version of the MSDN code to launch processes from a service in a user’s session which is available here: https://code.msdn.microsoft.com/windowsapps/CSCreateProcessAsUserFromSe-b682134e#content

When the service is triggered, it will happily launch Notepad in the user’s session if the launchpath variable I specify has a value of C:\Windows\sysnative\notepad.exe

However, if I try to call my other WinForms application with the command line:

Where <0>is replaced by:

and the other two placeholders ( <1>and <2>) are replaced by launch arguments, the machine on which the service runs logs system error code 123, which this link https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes—0-499-) tells me means «The filename, directory name, or volume label syntax is incorrect.»

I have tried hard-coding the path, moving the WinForms application so the execution path is also in c:\windows\sysnative however nothing seems to work, I always get the same error in the logs and the application doesn’t load. If I make a shortcut to the kiosk.exe application so I can pass in some test arguments, it launches fine.

Has anyone else ever encountered this? I’d be grateful for any advice.

C# Launch application with multiple arguments

I have been trying to start an application from a C# application but it fails to start properly. From the cmd the application plus the arguments launch a small window showing the output then the application in minimized to the system tray.

Launching the application from the C# application using the code below results in the process appearing in the task manager but nothing else, no output window, no system tray icon. What could be the issue?

also tried passing the following

also did not work. Would really appreciate any help on how to tackle this.

UPDATE: I think the issue maybe the multiple arguments that are to be passed to the process

4 Answers 4

I don’t see any mistake in your code. I have written a little program that prints out its args to the console

and then I have put it in C:, being the name of the app «PrintingArgs.exe», so I have written another one that executes the first:

this gives me the desired output of the list of numbers. The app that calls PrintingArgs exits as it reachs p.Start(), this could be avoided by using p.WaitForExit(); or just Console.Read(); . Also I have used both p.UseShellExecute and p.CreateNoWindow . Only in the case that

makes the PrintingArgs app not to show a window (even if I put only p.CreateNoWindow = true it shows a window).

Now it comes to my mind that maybe your are passing the args in a wrong way and makes the other program to fail and close inmediately, or maybe you are not pointing to the right file. Check paths and names, in order to find any mistake you could omit. Also, using

does not uses the info you set up with StartInfo into your Process instance.

How do I call ::CreateProcess in c++ to launch a Windows executable?

Looking for an example that:

  1. Launches an EXE
  2. Waits for the EXE to finish.
  3. Properly closes all the handles when the executable finishes.

8 Answers 8

Something like this:

Just replace the argv[1] with your constant or variable containing the program.

If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.

Something like the untested code below might be better as it will keep processing the windows message queue and your application will remain responsive:

if your exe happens to be a console app, you might be interested in reading the stdout and stderr — for that, I’ll humbly refer you to this example:

It’s a bit of a mouthful of code, but I’ve used variations of this code to spawn and read.

On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can’t do so using CreateProcess() on Vista since it won’t trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.

Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.

Bear in mind that using WaitForSingleObject can get you into trouble in this scenario. The following is snipped from a tip on my website:

The problem arises because your application has a window but isn’t pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won’t return to the new application until all applications have handled the message — but your app can’t handle the message because it isn’t pumping messages. so the new app locks up, so your wait never succeeds. DEADLOCK.

If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.

The only safe ways round this are:

  1. split off the Wait into a separate thread, or
  2. use a timeout on the Wait and use PeekMessage in your Wait loop to ensure that you pump messages, or
  3. use the MsgWaitForMultipleObjects API.

C# — Launch Invisible Process (CreateNoWindow & WindowStyle not working?)

I have 2 programs (.exe) which I’ve created in .NET. We’ll call them the Master and the Worker. The Master starts 1 or more Workers. The Worker will not be interacted with by the user, but it is a WinForms app that receives commands and runs WinForms components based on the commands it receives from the Master.

I want the Worker app to run completely hidden (except showing up in the Task Manager of course). I thought that I could accomplish this with the StartInfo.CreateNoWindow and StartInfo.WindowStyle properties, but I still see the Client.exe window and components in the form. However, it doesn’t show up in the taskbar.

What do I need to do to let Client.exe run, but not show up?ㅤㅤㅤㅤㅤ

4 Answers 4

Your usage of CreateNoWindow / WindowStyle works fine on my system with notepad.exe (e.g. it is hidden but running in the background), so it’s probably something the WinForms app is doing. Some ideas:

Option 1: If you control the WinForms worker process, you can override Control.SetVisibleCore to always hide the form. If you don’t want to always hide it, you can pass a command-line argument to it, e.g. /hide that will cause it to be hidden. Example (assuming there’s already code-behind for the form):

With this, running MyForm.exe results in a process with a visible form. Running MyForm.exe /hide results in a process with a hidden form. You could pass the /hide argument from your master process, so then normal users running the application will still see it.

Option 2: You can hide the application after it starts by doing a P/Invoke to ShowWindow . More info on this here. This has the drawback that you can sometimes see the worker window flicker into existence before being hidden. Example:

Process Класс

Определение

Предоставляет доступ к локальным и удаленным процессам и позволяет запускать и останавливать локальные системные процессы. Provides access to local and remote processes and enables you to start and stop local system processes.

Примеры

В следующем примере для запуска процесса используется экземпляр класса Process. The following example uses an instance of the Process class to start a process.

В следующем примере для запуска процесса используется сам класс Process и его статический метод Start. The following example uses the Process class itself and a static Start method to start a process.

Читайте также:  Check all ports used windows

В следующем примере на F# задается функция runProc , которая запускает процесс, получает все выходные данные и сведения об ошибках и записывает время выполнения процесса в миллисекундах. The following F# example defines a runProc function that starts a process, captures all output and error information, and records the number of milliseconds that the process has run. Функция runProc имеет три параметра: имя запускаемого приложения, аргументы для передачи в приложение и начальный каталог. The runProc function has three parameters: the name of application to launch, the arguments to supply to the application, and the starting directory.

Код функции runProc был написан ImaginaryDevelopment и доступен на условиях лицензии Microsoft Public License. The code for the runProc function was written by ImaginaryDevelopment and is available under the Microsoft Public License.

Комментарии

Компонент Process предоставляет доступ к процессу, который выполняется на компьютере. A Process component provides access to a process that is running on a computer. Процесс, упрощенно говоря, представляет из себя работающее приложение. A process, in the simplest terms, is a running app. Поток — это базовая единица, которой операционная система выделяет время процессора. A thread is the basic unit to which the operating system allocates processor time. Поток может исполнять любую часть кода процесса, включая части, выполняющиеся в данный момент другим потоком. A thread can execute any part of the code of the process, including parts currently being executed by another thread.

Компонент Process — это полезное средство для запуска, остановки, контроля и мониторинга приложений. The Process component is a useful tool for starting, stopping, controlling, and monitoring apps. Компонент Process можно использовать для получения списка запущенных процессов или для запуска нового процесса. You can use the Process component, to obtain a list of the processes that are running, or you can start a new process. Process используется для доступа к системным процессам. A Process component is used to access system processes. После инициализации компонента Process его можно использовать для получения сведений о запущенном процессе. After a Process component has been initialized, it can be used to obtain information about the running process. Эти сведения включают в себя набор потоков, загруженные модули (файлы .dll и .exe) и информацию о производительности, например объем памяти, используемой процессом. Such information includes the set of threads, the loaded modules (.dll and .exe files), and performance information such as the amount of memory the process is using.

Этот тип реализует интерфейс IDisposable. This type implements the IDisposable interface. По окончании использования выдаленную ему память следует прямо или косвенно освободить. When you have finished using the type, you should dispose of it either directly or indirectly. Чтобы сделать это прямо, вызовите его метод Dispose в блоке try / finally . To dispose of the type directly, call its Dispose method in a try / finally block. Чтобы сделать это косвенно, используйте языковые конструкции, такие как using (в C#) или Using (в Visual Basic). To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Дополнительные сведения см. в разделе «Использование объекта, реализующего IDisposable» в статье об интерфейсе IDisposable. For more information, see the «Using an Object that Implements IDisposable» section in the IDisposable interface topic.

32-разрядные процессы не могут получить доступ к модулям 64-разрядных процессов. 32-bit processes cannot access the modules of a 64-bit process. При попытке получить сведения о 64-разрядном процессе из 32-разрядного процесса вы получите исключение Win32Exception. If you try to get information about a 64-bit process from a 32-bit process, you will get a Win32Exception exception. С другой стороны, 64-разрядный процесс может получить доступ к модулям 32-разрядного процесса. A 64-bit process, on the other hand, can access the modules of a 32-bit process.

Компонент Process получает сведения о группе свойств одновременно. The process component obtains information about a group of properties all at once. После того, как компонент Process получит информацию о хотя бы одном члене любой группы, он будет кэшировать значения для других свойств в этой группе и не будет получать новые сведения о других членах группы до вызова метода Refresh. After the Process component has obtained information about one member of any group, it will cache the values for the other properties in that group and not obtain new information about the other members of the group until you call the Refresh method. Таким образом, значение свойства не обязательно будет новее, чем в момент последнего вызова метода Refresh. Therefore, a property value is not guaranteed to be any newer than the last call to the Refresh method. Схемы разделения на группы зависят от операционной системы. The group breakdowns are operating-system dependent.

Если в системе объявлен заключенный в кавычки путь в переменной path, при запуске любого процесса из этого расположения необходимо указание полного пути. If you have a path variable declared in your system using quotes, you must fully qualify that path when starting any process found in that location. В противном случае система не найдет этот путь. Otherwise, the system will not find the path. Например, если в переменной path нет пути c:\mypath и он добавляется к ней с использованием кавычек ( path = %path%;»c:\mypath» ), при запуске любого процесса из c:\mypath необходимо полностью указывать путь к файлу. For example, if c:\mypath is not in your path, and you add it using quotation marks: path = %path%;»c:\mypath» , you must fully qualify any process in c:\mypath when starting it.

Системный процесс однозначно идентифицируется в системе идентификатором процесса. A system process is uniquely identified on the system by its process identifier. Как и многие ресурсы Windows, процесс также идентифицируется его дескриптором, который не обязательно является уникальным в пределах одного компьютера. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. Дескриптор — это универсальный термин, обозначающий идентификатор ресурса. A handle is the generic term for an identifier of a resource. Операционная система сохраняет дескриптор процесса, доступный через свойство Handle компонента Process, даже после завершения процесса. The operating system persists the process handle, which is accessed through the Handle property of the Process component, even when the process has exited. Таким образом, можно получить административную информацию о процессе, например ExitCode (обычно ноль в случае успешного завершения или ненулевой код ошибки) и ExitTime. Thus, you can get the process’s administrative information, such as the ExitCode (usually either zero for success or a nonzero error code) and the ExitTime. Дескрипторы являются чрезвычайно важным ресурсом, поэтому утечка дескрипторов более опасна, чем утечка памяти. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory.

Этот класс содержит требования связывания и наследования на уровне класса, которые применяются ко всем элементам. This class contains a link demand and an inheritance demand at the class level that applies to all members. Если непосредственно вызывающий оператор или производный класс не имеет разрешения полного доверия, возникает исключение SecurityException. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. Дополнительные сведения о требованиях безопасности см. в разделе Требования связывания. For details about security demands, see Link Demands.

Заметки .NET Core .NET Core Notes

В .NET Framework класс Process по умолчанию использует кодировки Console, которые обычно являются кодовыми страницами, для потоков ввода, вывода и ошибок. In the .NET Framework, the Process class by default uses Console encodings, which are typically code page encodings, for the input, output, and error streams. Например, в системах, где в настройках языка и региональных параметров установлен английский (США), кодировкой по умолчанию для класса Console является кодовая страница 437. For example code, on systems whose culture is English (United States), code page 437 is the default encoding for the Console class. Однако в .NET Core может быть доступно только ограниченное подмножество этих кодировок. However, .NET Core may make only a limited subset of these encodings available. Если это так, в качестве кодировки по умолчанию будет использоваться Encoding.UTF8. If this is the case, it uses Encoding.UTF8 as the default encoding.

Если объект Process зависит от конкретных кодовых страниц, вы можете по-прежнему сделать их доступными, выполнив указанные ниже действия перед вызовом любых методов класса Process: If a Process object depends on specific code page encodings, you can still make them available by doing the following before you call any Process methods:

Читайте также:  При включении windows запускается восстановление системы

Добавьте в проект ссылку на сборку System.Text.Encoding.CodePages.dll. Add a reference to the System.Text.Encoding.CodePages.dll assembly to your project.

Передайте объект EncodingProvider в метод Encoding.RegisterProvider, чтобы сделать доступными дополнительные кодировки, поддерживаемые поставщиком кодировки. Pass the EncodingProvider object to the Encoding.RegisterProvider method to make the additional encodings supported by the encoding provider available.

Класс Process будет автоматически использовать кодировку системы по умолчанию вместо UTF8 при условии, что вы зарегистрировали поставщик кодировки перед вызовом любых методов класса Process. The Process class will then automatically use the default system encoding rather than UTF8, provided that you have registered the encoding provider before calling any Process methods.

Конструкторы

Инициализирует новый экземпляр класса Process. Initializes a new instance of the Process class.

Свойства

Получает базовый приоритет связанного процесса. Gets the base priority of the associated process.

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

(Унаследовано от Component) Container

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

(Унаследовано от Component) DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

(Унаследовано от Component) EnableRaisingEvents

Получает или задает значение, указывающее, следует ли вызывать событие Exited при прекращении процесса. Gets or sets whether the Exited event should be raised when the process terminates.

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

(Унаследовано от Component) ExitCode

Получает значение, заданное связанным процессом при завершении. Gets the value that the associated process specified when it terminated.

Получает время завершения связанного процесса. Gets the time that the associated process exited.

Получает собственный дескриптор связанного процесса. Gets the native handle of the associated process.

Получает число дескрипторов, открытых процессом. Gets the number of handles opened by the process.

Получает значение, определяющее завершение связанного процесса. Gets a value indicating whether the associated process has been terminated.

Получает уникальный идентификатор связанного процесса. Gets the unique identifier for the associated process.

Получает имя компьютера, на котором выполняется связанный процесс. Gets the name of the computer the associated process is running on.

Получает главный модуль связанного процесса. Gets the main module for the associated process.

Получает дескриптор главного окна связанного процесса. Gets the window handle of the main window of the associated process.

Получает заголовок главного окна процесса. Gets the caption of the main window of the process.

Получает или задает максимальный допустимый размер рабочего множества (в байтах) для связанного процесса. Gets or sets the maximum allowable working set size, in bytes, for the associated process.

Возвращает или задает минимальный допустимый размер рабочего множества (в байтах) для связанного процесса. Gets or sets the minimum allowable working set size, in bytes, for the associated process.

Получает модули, которые были загружены связанным процессом. Gets the modules that have been loaded by the associated process.

Возвращает объем невыгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.

Возвращает объем невыгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.

Возвращает объем выгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of paged memory, in bytes, allocated for the associated process.

Возвращает объем выгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of paged memory, in bytes, allocated for the associated process.

Возвращает объем выгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of pageable system memory, in bytes, allocated for the associated process.

Возвращает объем выгружаемой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of pageable system memory, in bytes, allocated for the associated process.

Получает максимальный объем памяти в байтах в файле подкачки виртуальной памяти, используемой связанным процессом. Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated process.

Получает максимальный объем памяти в байтах в файле подкачки виртуальной памяти, используемой связанным процессом. Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated process.

Получает максимальный объем виртуальной памяти (в байтах), используемой связанным процессом. Gets the maximum amount of virtual memory, in bytes, used by the associated process.

Получает максимальный объем виртуальной памяти (в байтах), используемой связанным процессом. Gets the maximum amount of virtual memory, in bytes, used by the associated process.

Возвращает максимальный размер рабочего множества для связанного процесса (в байтах). Gets the peak working set size for the associated process, in bytes.

Получает максимальный объем физической памяти (в байтах), используемой связанным процессом. Gets the maximum amount of physical memory, in bytes, used by the associated process.

Возвращает или задает значение, указывающее, должна ли операционная система временно увеличить приоритет связанного процесса, когда основное окно процесса получит фокус. 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.

Возвращает или задает общую категорию приоритета для процесса. Gets or sets the overall priority category for the associated process.

Получает объем закрытой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of private memory, in bytes, allocated for the associated process.

Получает объем закрытой системной памяти в байтах, выделенной для связанного процесса. Gets the amount of private memory, in bytes, allocated for the associated process.

Получает права доступа на время процессора для этого процесса. Gets the privileged processor time for this process.

Получает имя процесса. Gets the name of the process.

Получает или задает процессоры, на которых может быть запланировано выполнение потоков данного процесса. Gets or sets the processors on which the threads in this process can be scheduled to run.

Получает значение, указывающее, отвечает или нет пользовательский интерфейс. Gets a value indicating whether the user interface of the process is responding.

Получает собственный дескриптор процесса. Gets the native handle to this process.

Получает идентификатор сеанса служб терминалов для связанного процесса. Gets the Terminal Services session identifier for the associated process.

Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.

(Унаследовано от Component) StandardError

Получает поток, используемый для чтения вывода ошибок приложения. Gets a stream used to read the error output of the application.

Получает поток, используемый для записи ввода приложения. Gets a stream used to write the input of the application.

Получает поток, используемый для чтения текстовых выходных данных приложения. Gets a stream used to read the textual output of the application.

Получает или задает свойства для передачи их методу Start() объекта Process. Gets or sets the properties to pass to the Start() method of the Process.

Получает время запуска связанного процесса. Gets the time that the associated process was started.

Получает или задает объект, используемый для маршалинга вызовов обработчика событий, происходящих в результате события завершения процесса. Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event.

Получает множество потоков, выполняющихся в связанном процессе. Gets the set of threads that are running in the associated process.

Получает полное время процессора для этого процесса. Gets the total processor time for this process.

Получает пользовательское время процессора для этого процесса. Gets the user processor time for this process.

Получает размер виртуальной памяти процесса (в байтах). Gets the size of the process’s virtual memory, in bytes.

Возвращает объем виртуальной памяти в байтах, выделенной для связанного процесса. Gets the amount of the virtual memory, in bytes, allocated for the associated process.

Возвращает использование физической памяти связанного процесса (в байтах). Gets the associated process’s physical memory usage, in bytes.

Получает объем физической памяти в байтах, выделенной для связанного процесса. Gets the amount of physical memory, in bytes, allocated for the associated process.

Методы

Начинает операции асинхронного чтения с перенаправленного потока StandardError приложения. Begins asynchronous read operations on the redirected StandardError stream of the application.

Начинает операции асинхронного чтения с перенаправленного потока StandardOutput приложения. Begins asynchronous read operations on the redirected StandardOutput stream of the application.

Читайте также:  Не подключается андроид linux

Отменяет операцию асинхронного чтения в перенаправленном потоке StandardError приложения. Cancels the asynchronous read operation on the redirected StandardError stream of an application.

Отменяет операцию асинхронного чтения в перенаправленном потоке StandardOutput приложения. Cancels the asynchronous read operation on the redirected StandardOutput stream of an application.

Освобождает все ресурсы, связанные с этим компонентом. Frees all the resources that are associated with this component.

Закрывает процесс, имеющий пользовательский интерфейс, посылая сообщение о закрытии главному окну процесса. Closes a process that has a user interface by sending a close message to its main window.

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) Dispose()

Выполняет определяемые приложением задачи, связанные с удалением, высвобождением или сбросом неуправляемых ресурсов. Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Освобождает все ресурсы, используемые этим процессом. Release all resources used by this process.

Помещает компонент Process в состояние взаимодействия с работающим системным процессом, выполняющимся в специальном режиме путем включения встроенного свойства SeDebugPrivilege в данном потоке. Puts a Process component in state to interact with operating system processes that run in a special mode by enabling the native property SeDebugPrivilege on the current thread.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetCurrentProcess()

Получает новый компонент Process и связывает его с активным в данный момент процессом. Gets a new Process component and associates it with the currently active process.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetProcessById(Int32)

Возвращает новый компонент Process, по заданному идентификатору процесса на локальном компьютере. Returns a new Process component, given the identifier of a process on the local computer.

Возвращает новый компонент Process по заданному идентификатору процесса и имени компьютера в сети. Returns a new Process component, given a process identifier and the name of a computer on the network.

Создает новый компонент Process для каждого ресурса процесса на локальном компьютере. Creates a new Process component for each process resource on the local computer.

Создает новый компонент Process для каждого ресурса процесса на указанном компьютере. Creates a new Process component for each process resource on the specified computer.

Создает массив из новых компонентов Process и связывает их со всеми ресурсами процесса на локальном компьютере, для которых заданное имя процесса является общедоступным. Creates an array of new Process components and associates them with all the process resources on the local computer that share the specified process name.

Создает массив из новых компонентов Process и связывает их со всеми ресурсами процесса на удаленном компьютере, для которых заданное имя процесса является общедоступным. Creates an array of new Process components and associates them with all the process resources on a remote computer that share the specified process name.

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

(Унаследовано от Component) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) Kill()

Немедленно останавливает связанный процесс. Immediately stops the associated process.

Немедленно останавливает связанный процесс и, при необходимости, его дочерние процессы. Immediately stops the associated process, and optionally its child/descendent processes.

Выбирает компонент Process из состояния, позволяющего ему взаимодействовать с процессами операционной системы, запущенными в специальном режиме. Takes a Process component out of the state that lets it interact with operating system processes that run in a special mode.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) OnExited()

Вызывает событие Exited. Raises the Exited event.

Удаляет любые кэшированные внутри компонента процесса сведения о связанном процессе. Discards any information about the associated process that has been cached inside the process component.

Запускает (или повторно использует) ресурс процесса, определенный свойством StartInfo этого компонента Process, и связывает его с компонентом. Starts (or reuses) the process resource that is specified by the StartInfo property of this Process component and associates it with the component.

Запускает ресурс процесса, определенный параметром, содержащим стартовую информацию процесса (например, имя файла запускаемого процесса), и связывает ресурс с новым компонентом Process. 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 Process component.

Запускает ресурс процесса путем указания имени документа или файла приложения и связывает ресурс с новым компонентом Process. Starts a process resource by specifying the name of a document or application file and associates the resource with a new Process component.

Запускает ресурс процесса путем указания имени приложения и набора аргументов командной строки. Starts a process resource by specifying the name of an application and a set of command line arguments.

Запускает ресурс процесса путем указания имени приложения и набора аргументов командной строки и связывает ресурс с новым компонентом Process. 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 Process component.

Запускает ресурс процесса путем указания имени приложения, имени пользователя, пароля и домена и связывает ресурс с новым компонентом Process. 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 Process component.

Запускает ресурс процесса путем указания имени приложения, набора аргументов командной строки, имени пользователя, пароля и домена и связывает ресурс с новым компонентом Process. 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 Process component.

Преобразует имя процесса в строку, объединенную с родительским типом компонента, если это применимо. Formats the process’s name as a string, combined with the parent component type, if applicable.

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

(Унаследовано от Object) WaitForExit()

Дает компоненту Process команду ожидать завершения связанного процесса в течение неограниченного времени. Instructs the Process component to wait indefinitely for the associated process to exit.

Дает компоненту Process команду ожидать завершения связанного процесса в течение указанного времени в миллисекундах. Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.

Указывает компоненту процесса ожидать завершения связанного процесса или отмены cancellationToken . Instructs the process component to wait for the associated process to exit, or for the cancellationToken to be cancelled.

Дает компоненту Process команду ожидать перехода связанного процесса в состояние простоя в течение неограниченного времени. Causes the 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.

Дает компоненту Process команду ожидать входа связанного процесса в состояние простоя в течение указанного времени в миллисекундах. Causes the 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.

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

(Унаследовано от Component) ErrorDataReceived

Происходит, когда приложение выполняет запись в свой перенаправленный поток StandardError. Occurs when an application writes to its redirected StandardError stream.

Происходит при завершении процесса. Occurs when a process exits.

Происходит, когда приложение записывает строку в свой перенаправленный поток StandardOutput. Occurs each time an application writes a line to its redirected StandardOutput stream.

Оцените статью