c# - Windows 应用程序 - 处理 taskkill

标签 c# windows process

我有一个 C# 应用程序,它的 Output Type 设置为 Windows Application,所以它基本上只是一个在后台运行的进程。我可以在任务管理器中看到该进程,我试图从命令行优雅地终止它,并且还能够在我的代码中处理这个终止。我运行了 taskkill/im myprocess.exe 并且消息是

SUCCESS: Sent termination signal to the process "MyProcess.exe" with PID 61

我的问题是此后我仍然可以在任务管理器中看到进程。如果我执行 taskkill/f 它会关闭它,但我肯定不希望这样,因为我需要在我的进程退出之前运行代码。

我如何在我的应用程序中处理这个“终止信号”,以便我可以执行必要的退出前操作然后退出?

最佳答案

如果您查看taskkill 实际做了什么you will find它向进程的消息循环发送一条 WM_CLOSE 消息。所以你需要找到一种方法来处理这个消息并退出应用程序。

下面的小测试应用程序展示了一种方法来做到这一点。如果您使用 CTRL+F5 快捷方式从 Visual Studio 运行它(以便该进程在调试器之外运行),您实际上可以使用 taskkill/IM 关闭它[进程名称]

using System;
using System.Security.Permissions;
using System.Windows.Forms;

namespace TaskKillTestApp
{
    static class Program
    {
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        private class TestMessageFilter : IMessageFilter
        {
            public bool PreFilterMessage(ref Message m)
            {
                if (m.Msg == /*WM_CLOSE*/ 0x10)
                {
                    Application.Exit();
                    return true;
                }
                return false;
            }
        }

        [STAThread]
        static void Main()
        {
            Application.AddMessageFilter(new TestMessageFilter());
            Application.Run();
        }
    }
}

关于c# - Windows 应用程序 - 处理 taskkill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38480722/

相关文章:

无法使用 getppid() 获取预期的 id

c# - IOrderedEnumerable 的 LINQ 优化

c# - 用 C# 编写二进制文件,然后用 C++ 读取同一文件

c# - MSBuild 15 - 命名空间中不存在类型或命名空间 'Fakes'

c - _popen 崩溃[Windows - C]

javascript - 如何重新启动 Node.js 子进程

c# - ScrollView 在 Xamarin Forms 中的另一个 ScrollView 中

c# - 如何快速创建内容为 "natural"的大型 (>1gb) 文本+二进制文件? (C#)

c++ - MinGW,g++,winapi,winsdk,迷茫中

c++ - 创建2个子进程