Windows command close process

TaskKill: Kill process from command line (CMD)

We can kill a process from GUI using Task manager. If you want to do the same from command line., then taskkill is the command you are looking for. This command has got options to kill a task/process either by using the process id or by the image file name.

Kill a process using image name:

We can kill all the processes running a specific executable using the below command.

Example:
Kill all processes running mspaint.exe:

Kill a process forcibly

In some cases, we need to forcibly kill applications. For example, if we try to to kill Internet explorer with multiple tabs open, tasklist command would ask the user for confirmation. We would need to add /F flag to kill IE without asking for any user confirmation.

/F : to forcibly kill the process. If not used, in the above case it will prompt the user if the opened pages in tabs need to be saved.

To kill Windows explorer, the following command would work

The above command would make all GUI windows disappear. You can restart explorer by running ‘explorer’ from cmd.

Not using /F option, would send a terminate signal. In Windows 7, this throws up a shutdown dialog to the user.

Kill a process with process id:

We can use below command to kill a process using process id(pid).

Example:
Kill a process with pid 1234.

Kill processes consuming high amount of memory

For example, to kill processes consuming more than 100 MB memory, we can run the below command

More examples

Sometimes applications get into hung state when they are overloaded or if the system is running with low available memory. When we can’t get the application to usable state, and closing the application does not work, what we usually tend to do is kill the task/process. This can be simply done using taskkill command.

To kill Chrome browser from CMD

Kill Chromedirver from command line

To kill firefox browser application

To kill MS Word application(Don’t do this if you haven’t saved your work)

Sometimes, the command window itself might not be responding. You can open a new command window and kill all the command windows

This even kills the current command window from which you have triggered the command.

i have a question about this.
I have a process that runs in my domain that puts outlook suspended. As soon as I do a task kill forced as administrator it runs.

I wrote a little script, now i want to add admin rights to the script via GPO.

Закрыть программы из командной строки (Windows)

Как правильно закрыть / закрыть программы из командной строки, аналогично нажатию кнопки закрытия «X» в углу окна?

Я пытаюсь закрыть Chrome под 3 различными версиями Windows: Win7 Ultimate, Win7 Home, WinXP

Под Ultimate и XP: TSKILL chrome

Под домом TASKKILL /IM chrome.exe

(Он закрывает chrome, нет ошибок cmd,
но при повторном запуске восстанавливается ошибка chrome )

TASKKILL /IM chrome.exe :

(Он закрывает Chrome, нет ошибок Chrome при повторном запуске,
но ошибки в cmd: «невозможно завершить дочерние процессы (около 4-5), только принудительно с помощью /F »)

Должен ли я игнорировать дочерние ошибки cmd, если при повторном запуске Chrome не показывает ошибок ?

Правильный способ закрыть / закрыть программу в конечном итоге зависит от программного обеспечения. Однако, как правило, рекомендуется закрывать программы Windows всякий раз, когда они получают сообщение WM_CLOSE. Правильно освобождая память и закрывая ручки. Существуют и другие сообщения, которые могут сигнализировать о закрытии приложения, но как автор обрабатывает каждое сообщение, зависит от автора программного обеспечения.

taskkill отправляет сообщение WM_CLOSE, и затем дело за приложением, правильно ли закрыть. Вы также можете использовать эту /T опцию для сигнализации дочерних процессов.

Используйте эту /F опцию, только если вы хотите принудительно завершить процесс.

Читайте также:  Джойстик ps3 windows bluetooth

Другие варианты включают отправку клавиш Alt + F4, использование PowerShell или сторонних приложений.

Обновить до обновленного вопроса

Проигнорируйте ошибки. Хром генерирует много процессов. Ошибки возникают, когда процесс не подтверждает сообщение WM_CLOSE, которое отправляет TASKKILL. Только процессы с циклом сообщений смогут получать сообщение, поэтому процессы, у которых нет цикла сообщений, будут генерировать эту ошибку. Скорее всего, эти процессы являются расширениями и плагинами Chrome.

Чтобы скрыть ошибки захвата вывода

Описание: TASKKILL — это правильный способ с помощью командной строки закрывать приложения в соответствии с его реализацией WM_CLOSE и Microsoft KB, которую я связал .

Он имеет команду «closeprocess», которая предназначена для корректного закрытия процессов. Согласно его документу, он не завершает приложения, а отправляет WM_CLOSE все окна верхнего уровня целевого процесса.

Если это не сработает, держу пари, в вашем приложении необычная процедура очистки. Я хотел бы посмотреть, что происходит внутри, поэтому, пожалуйста, дайте мне знать, какое у вас целевое приложение.

Ответ на этот вопрос можно найти here ( ссылка Microsoft ).

Вы можете отправлять WM_CLOSE сообщения в любое окно, которое хотите закрыть. Многие окна обрабатывают, WM_CLOSE чтобы предложить пользователю сохранить документы.

Инструмент, который делает это правильно @Kill . Смотрите также SendMsg .

Я не знаю, как сделать это в пакетном режиме, но вы могли бы использовать VBScript для этого. Имитация клавиш Alt + F4 (приравнивается к сигналу WM_CLOSE ).

Запустите и посмотрите на поведение этого скрипта ниже.

Here это список ключей имен для SendKeys.

Когда вы запускаете скрипт, блокнот открыт, некоторые слова пишутся, а затем подается сигнал о закрытии программы, см. Рисунок ниже.

Дополнительный вопрос

Можно ли запустить свернутую программу или фон с vbscript?

Да. Используйте следующий код:

Для получения дополнительной информации проверьте Run Method .

Может ли Chrome перейти на какой-либо URL-адрес в VBScript?

Если по умолчанию используется chrome, используйте:

Есть ли способ привлечь внимание к конкретному приложению ( chrome.exe )?

Я хочу отправить alt + f4 ТОЛЬКО в Chrome, независимо от того, что я делаю с другими окнами.

Следующий код работает на Windows 8 .

Существуют некоторые утилиты командной строки, которые могут отправлять подходящее WM_SYSCOMMAND сообщение ( SC_CLOSE в качестве команды) в окно верхнего уровня программы. Я уверен, что по крайней мере один будет упомянут в ближайшее время. (Тогда кто-то упомянет AutoIt. Тогда будет ответ, показывающий, как это сделать с помощью PowerShell и CloseMainWindow() .)

Вызывается утилита командной строки, которая поставляется как встроенная команда в TCC JP Software , интерпретаторе команд и процессоре сценариев команд для Windows TASKEND .

Хорошо, не собираюсь лгать. Я видел это на stackoverflow и думал, что это сложный вопрос. Тааак я только что провел последние 2 часа, написав код. И вот оно .

Выполнив следующие действия, вы можете набрать «TaskClose notepad.exe» после нажатия «Пуск», и он автоматически сохранит все недокументированные файлы блокнота на рабочем столе. Он автоматически закроет chrome.exe и сохранит настройки восстановления.

Вы можете добавлять и удалять дополнительные настройки для других приложений в условиях if. Например:

VBS и командные файлы выполняют следующие процедуры:

  • Собирает исполняемый файл.
  • Запрашивает имена исполняемых приложений из списка задач.
  • Выполняет процедуру «Alt + TAB (x)», пока не проверит, открыто ли окно.
  • Затем выполняет команды прокрутки, будь то «Alt + F4» или даже в крайних случаях
  • Alt + F4
  • Активировать Сохранить
  • AutoIncrememnt Имя файла
  • Выйти из приложения.

ReturnAppList.bat: установить в «C: \ windows \ system32 \»

TaskClose.bat: установить в «C: \ windows \ system32 \» И «C: \ Users \ YourUserName \»

TaskClose.vbs: установить в «C: \ windows \ system32 \»

Это было очень весело писать, и я больше рад закончить его, чем показывать ответ. Удачной недели!

Process. Close Main Window Метод

Определение

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

Возвращаемое значение

Значение true , если сообщение о закрытии было успешно отправлено; false , если связанный процесс не имеет главного окна или если главное окно отключено (например, если отображается модальное диалоговое окно). true if the close message was successfully sent; 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).

Исключения

Этот процесс уже завершился. The process has already exited.

-или- -or- Нет процессов, связанных с этим объектом Process. No process is associated with this Process object.

Читайте также:  Компьютер не видит второй монитор через vga материнской платы windows 10

Примеры

В следующем примере запускается экземпляр блокнота. The following example starts an instance of Notepad. Затем он получает сведения об использовании физической памяти для связанного процесса с интервалом в 2 секунды в течение не более 10 секунд. It then retrieves the physical memory usage of the associated process at 2 second intervals for a maximum of 10 seconds. Пример определяет, завершается ли процесс до 10 секунд. The example detects whether the process exits before 10 seconds have elapsed. В этом примере процесс закрывается, если он по-прежнему выполняется через 10 секунд. The example closes the process if it is still running after 10 seconds.

Комментарии

При выполнении процесса его цикл обработки сообщений находится в состоянии ожидания. When a process is executing, its message loop is in a wait state. Цикл обработки сообщений выполняется каждый раз, когда операционная система отправляет сообщение Windows в процесс. The message loop executes every time a Windows message is sent to the process by the operating system. Вызов CloseMainWindow отправляет запрос на закрытие главного окна, которое в правильно сформированном приложении закрывает дочерние окна и отменяет все выполняющиеся циклы обработки сообщений для приложения. Calling CloseMainWindow sends a request to close the main window, which, in a well-formed application, closes child windows and revokes all running message loops for the application. Запрос на выход из процесса путем вызова не CloseMainWindow заставляет приложение завершить работу. The request to exit the process by calling CloseMainWindow does not force the application to quit. Приложение может запросить проверку пользователя перед выходом или отказаться от его завершения. The application can ask for user verification before quitting, or it can refuse to quit. Чтобы принудительно завершить работу приложения, используйте Kill метод. To force the application to quit, use the Kill method. Поведение аналогично тому CloseMainWindow , как пользователь закрывает главное окно приложения с помощью системного меню. The behavior of CloseMainWindow is identical to that of a user closing an application’s main window using the system menu. Таким образом, запрос на завершение процесса путем закрытия главного окна не заставляет приложение немедленно завершить работу. Therefore, the request to exit the process by closing the main window does not force the application to quit immediately.

Данные, измененные процессом или ресурсами, выделенными для процесса, могут быть потеряны при вызове Kill . Data edited by the process or resources allocated to the process can be lost if you call Kill. Kill вызывает аварийное завершение процесса и должно использоваться только при необходимости. Kill causes an abnormal process termination, and should be used only when necessary. CloseMainWindow включает упорядоченное завершение процесса и закрывает все окна, поэтому оно является предпочтительным для приложений с интерфейсом. CloseMainWindow enables an orderly termination of the process and closes all windows, so it is preferable for applications with an interface. CloseMainWindowВ случае сбоя можно использовать Kill для завершения процесса. If CloseMainWindow fails, you can use Kill to terminate the process. Kill является единственным способом завершения процессов, не имеющих графических интерфейсов. Kill is the only way to terminate processes that do not have graphical interfaces.

Можно вызывать Kill и CloseMainWindow только для процессов, запущенных на локальном компьютере. You can call Kill and CloseMainWindow only for processes that are running on the local computer. Нельзя вызвать завершение процессов на удаленных компьютерах. You cannot cause processes on remote computers to exit. Можно просматривать только сведения о процессах, запущенных на удаленных компьютерах. You can only view information for processes running on remote computers.

How to Kill a Process in Windows 10

When you start an app, the operating system creates a process for an executable file of the app. It contains the program code and its current activity. Windows assigns a special number known as Process Identifier (PID) which is unique for every process. There are a number of reasons you might want to kill a process, and different methods you can use to terminate it. Here is how it can be done.

To kill a process in Windows 10, do the following.

  1. Open Task Manager.
  2. Click on «More details» in the bottom right corner to enter Full view mode.
  3. Select the desired app in the app list.
  4. Click on the End task button or hit the Del key on the keyboard.
Читайте также:  Как отвязать windows 10 от цифровой лицензии

This is Task Manager’s most well known method.

Note: The same can be done from the Details tab. It is a special tab which lists process names instead of app names. There you can select a process in the list and either click on the End process button or hit the Del key.

Using the End Task button means Windows first tries to see for a certain timeout if the process has really stopped responding, and attempts to collect a crash or memory dump of the process. It then terminates the app.

Tip: We highly recommend you read the article How to end a process quickly with Task Manager in Windows 10 to learn all Task Manager tricks. Also, you can get the classic Task Manager app in Windows 10 to end processes or tasks.

Another classic method to close a process is the console tool taskill. It comes bundled with modern versions of Windows.

Kill a process using Taskkill

Note: Some processes are running as Administrator (elevated). In order to kill them, you need to open an elevated command prompt instance.

  1. Open the command prompt as the current user or as Administrator.
  2. Type tasklist to see the list of running processes and their PIDs. Since the list might be very long, you can use a pipe character with the more command.

  • To kill a process by its PID, type the command:
  • To kill a process by its name, type the command
  • For example, to kill a process by its PID:


    To kill a process by its name:


    Taskkill supports many useful options which you can use to terminate apps. You can learn them by running it as follows: taskkill /? . Using taskkill, you can close all not responding tasks at once in Windows 10.

    Kill a process using PowerShell

    Note: To kill a process which runs elevated, you need to open PowerShell as Administrator.

    1. Open PowerShell. If required, run it as Administrator.
    2. Type the command Get-Process to see the list of running processes.
    3. To kill a process by its name, execute the following cmdlet:
    4. To kill a process by its PID, run the command:

    Examples:
    This command will close the notepad.exe process.

    The next command will close a process with PID 2137.

    If you need to kill a Store app, see the following article:

    Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

    Share this post

    About Sergey Tkachenko

    Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

    10 thoughts on “ How to Kill a Process in Windows 10 ”

    Some good ways to kill a process, but you forgot Process Explorer, I have been using it since Microsoft bought his company. And have replaced Task Manager with it. Thanks for you description on killing a process with power shell….janek

    Well, i’ve tried to cover native methods. Sure, there are tons of extra ways to kill a process.

    Is there a way to have tasklist output sorted alphabetically? It truly is a long list.
    Thank You

    Try
    TASKLIST /NH | SORT

    tip: does not need to type anything in uppercase 😉

    Thank you for this information. I was trying to remote in to work but my outlook was stuck/frozen and could not access anything but command. The taskkill information saved me a long commute in to work.

    Thank you for your information on how to kill a Windows process.

    Could you possibly advise how to “restart” a process stopped by using taskkill in the command line?

    For example, how can taskhostw.exe be restarted in the command line after the using the command “taskkill /F /IM taskhostw.exe” in the command line?

    It depends on the process.
    If it is a service, you should issue the appropriate command for the service.
    If it is a regular executable, you need to start it by typing its executable name and its arguments, if they needed.
    Also, there is a start command in the command prompt. Run start /? to see what it can do for you.

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