我写了一个应用程序桌面工具栏(又名 AppBar),它工作得很好,除了如果我终止进程,AppBar 代码永远不会有机会通过发送 ABM_REMOVE 来清理。问题是这基本上把用户的桌面搞砸了。 AppBar 是使用互操作代码在 .NET 中编写的。

有没有人知道清理这个资源的方法,即使是在 TaskManager 进程终止的情况下?

最佳答案

从任务管理器中终止进程时,该应用程序中不会引发任何事件。通常使用单独的帮助程序来监听进程的 Win32_ProcessStopTrace 事件。为此,您可以使用 WqlEventQuery,它是 System.Management 的一部分。

这是来自 a MegaSolutions post 的一些示例代码。

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;


class ProcessObserver : IDisposable
{
    ManagementEventWatcher m_processStartEvent = null;
    ManagementEventWatcher m_processStopEvent = null;


    public ProcessObserver(string processName, EventArrivedEventHandler onStart, EventArrivedEventHandler onStop)
    {
        WqlEventQuery startQuery = new WqlEventQuery("Win32_ProcessStartTrace", String.Format("ProcessName='{0}'", processName));
        m_processStartEvent = new ManagementEventWatcher(startQuery);


        WqlEventQuery stopQuery = new WqlEventQuery("Win32_ProcessStopTrace", String.Format("ProcessName='{0}'", processName));
        m_processStopEvent = new ManagementEventWatcher(stopQuery);


        if (onStart != null)
            m_processStartEvent.EventArrived += onStart;


        if (onStop != null)
            m_processStopEvent.EventArrived += onStop;
    }


    public void Start()
    {
        m_processStartEvent.Start();
        m_processStopEvent.Start();
    }


    public void Dispose()
    {
        m_processStartEvent.Dispose();
        m_processStopEvent.Dispose();
    }
}

关于c# - 进程终止后清理 AppBar,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/307643/

10-10 23:38
查看更多