如何优雅地终止进程? [英] How to gracefully terminate a process?

查看:115
本文介绍了如何优雅地终止进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想终止多个进程,但我想给每个进程保存数据的机会,询问用户是否保存文件,甚至忽略关闭请求.

I want to terminate a number of processes, but I want to give each process the chance to save its data, ask the user about saving a file and even ignore the close request.

所以 TerminateProcess 是不可能的,因为它会立即终止进程.另一种方法是使用 SendMessage/PostMessageWM_CLOSE 发送到主窗口,不幸的是我对窗口一无所知进程,我只有进程 id,所以 FindWindow 也无济于事.有没有其他方法可以找到进程的主窗口?

So TerminateProcess is out of the question, because it kills the process instantly. Another way would be to use SendMessage/PostMessage to send a WM_CLOSE to the main window, unfortunately I don't know anything about the windows of the processes, I only have the process id, so FindWindow doesn't help either. Is there any other way to find the main windows of a process?

换句话说:有没有什么方法可以像 Windows 7 任务管理器那样优雅地终止 任何 进程,就像单击结束任务"时所做的那样?(而不是结束进程")

In other words: Is there any way to terminate any process gracefully just like the Windows 7 task manager did when you clicked on "End Task"? (and not "End Process")

推荐答案

EnumWindows 枚举进程中的所有顶级窗口.GetWindowThreadProcessId 获取每个线程的进程和Id.

EnumWindows enumerates all the top level windows in a process. GetWindowThreadProcessId gets the process and Id of each thread.

您现在有足够的信息可以正常关闭任何 GUI 应用程序.

You now have enough information to gracefully close any GUI application.

您可以将WM_CLOSE 消息发送到您希望关闭的任何窗口.许多窗口处理 WM_CLOSE 以提示用户保存文档.您可以使用 PostThreadMessage 向发现的线程发送 WM_QUIT 消息以引起消息循环终止.

You can send WM_CLOSE messages to any window you wish to close. Many windows handle WM_CLOSE to prompt the user to save documents.You can send a WM_QUIT message using PostThreadMessage to the discovered threads to cause the message loop to terminate.

不允许用户代码从不同的应用程序或线程调用 DestroyWindow 到窗口...如果应用程序没有响应 WM_CLOSEWM_QUIT 请求您返回 TerminateProcess 区域.

User code is not allowed to call DestroyWindow from a different app or thread to the windows... if the app does not respond to WM_CLOSE or WM_QUIT requests you're back in TerminateProcess land.

这不会关闭控制台应用程序,因为应用程序进程和拥有窗口的进程是不同的.

This will not close console applications as the application process, and process that owns the window, are different.

参考 T.s.下面是 Arun 对处理控制台应用程序的正确方法的回答.

Refer to T.s. Arun's answer below for the correct method for dealing with console applications.

这篇关于如何优雅地终止进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆