VC++进程管理,新进程启动时获取名字-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

VC++进程管理,新进程启动时获取名字

2016-03-06 11:25:31 2130 1

我是个刚学完Android,老板要把一个C#项目转成java的新人,有些操作不能用java完成,目前正在编写C++代码,遇到一个问题,需要做一个钩子,当有新进程启动时候我需要获取到这个进程的名字做一些操作,现有C#代码如下:

public class GlobalHook
{
//ManagementEventWatcher watch_del = null;
//[DllImport("user32.dll")]
//private static extern bool
//SetForegroundWindow(IntPtr hWnd);
//[DllImport("user32.dll")]
//private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
//[DllImport("user32.dll")]
//private static extern bool IsIconic(IntPtr hWnd);
//// 消息函数
//[DllImport("user32.dll", EntryPoint = "PostMessageA")]
//public static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    //[DllImport("user32.dll")]
    //public static extern IntPtr FindWindow(string strclassName, string strWindowName);
    //[DllImportAttribute("user32.dll")]
    //public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    //public const int WM_SYSCOMMAND = 0x0112;
    //public const int SC_MAXIMIZE = 0xF030;
    public static ManagementEventWatcher watch_crt = null;

    protected tray m_tray;

    public GlobalHook(tray mm_tray)
    {
        this.m_tray = mm_tray;
        StartWatchCreateProcess();

    }
    ~GlobalHook()
    {
        if (watch_crt != null)
            watch_crt.Stop();
    }
    protected void StartWatchCreateProcess()
    {
        WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent",
                     new TimeSpan(0, 0, 1),
                     "TargetInstance isa \"Win32_Process\"");
        watch_crt = new ManagementEventWatcher(query);
        watch_crt.EventArrived += new EventArrivedEventHandler(HandleProcessCreateEvent);
        watch_crt.Start();
    }

    //监视进程启动
    protected void HandleProcessCreateEvent(object sender, EventArrivedEventArgs e)
    {

        ManagementBaseObject MBO = (ManagementBaseObject)e.NewEvent["TargetInstance"];
        string temp = MBO["Name"].ToString();
        if (temp != "")
        {
            string name = temp;
            if (name.Contains("."))
                name = temp.Substring(0, temp.IndexOf("."));

            this.m_tray.CheckSingleProcessItemHook(name);
        }

    }

}

C++该怎样写?

取消 提交回答
全部回答(1)
  • a123456678
    2019-07-17 18:54:20
    #define _WIN32_DCOM
    #include <iostream>
    using namespace std;
    #include <comdef.h>
    #include <Wbemidl.h>
    #include <atlcomcli.h>
    
    #pragma comment(lib, "wbemuuid.lib")
    
    #include "ProcessTerminationNotification.h"
    
    class EventSink : public IWbemObjectSink
    {
        friend void ProcessTerminationNotification::registerTerminationCallback(TNotificationFunction callback, unsigned processId);
    
        CComPtr<IWbemServices> pSvc;
        CComPtr<IWbemObjectSink> pStubSink;
    
        LONG m_lRef;
        ProcessTerminationNotification::TNotificationFunction m_callback;
    
    public:
        EventSink(ProcessTerminationNotification::TNotificationFunction callback)
            : m_lRef(0) 
            , m_callback(callback)
        {}
        ~EventSink()
        {}
    
        virtual ULONG STDMETHODCALLTYPE AddRef()
        {
            return InterlockedIncrement(&m_lRef);
        }
        virtual ULONG STDMETHODCALLTYPE Release()
        {
            LONG lRef = InterlockedDecrement(&m_lRef);
            if (lRef == 0)
                delete this;
            return lRef;
        }
        virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv)
        {
            if (riid == IID_IUnknown || riid == IID_IWbemObjectSink)
            {
                *ppv = (IWbemObjectSink *) this;
                AddRef();
                return WBEM_S_NO_ERROR;
            }
            else return E_NOINTERFACE;
        }
    
        virtual HRESULT STDMETHODCALLTYPE Indicate( 
            LONG lObjectCount,
            IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
            )
        {
            m_callback();
            /* Unregister event sink since process is terminated */
            pSvc->CancelAsyncCall(pStubSink);
            return WBEM_S_NO_ERROR;
        }
    
        virtual HRESULT STDMETHODCALLTYPE SetStatus( 
            /* [in] */ LONG lFlags,
            /* [in] */ HRESULT hResult,
            /* [in] */ BSTR strParam,
            /* [in] */ IWbemClassObject __RPC_FAR *pObjParam
            )
        {
            return WBEM_S_NO_ERROR;
        } 
    
    };
    
    
    void ProcessTerminationNotification::registerTerminationCallback( TNotificationFunction callback, unsigned processId )
    {
        CComPtr<IWbemLocator> pLoc;
    
        HRESULT hres = CoCreateInstance(
            CLSID_WbemLocator,             
            0, 
            CLSCTX_INPROC_SERVER, 
            IID_IWbemLocator,
            (LPVOID*)&pLoc);
    
        if (FAILED(hres))
        {
            cout << "Failed to create IWbemLocator object. "
                << "Err code = 0x"
                << hex << hres << endl;
            throw std::exception("ProcessTerminationNotificaiton initialization failed");
        }
    
        // Step 4: ---------------------------------------------------
        // Connect to WMI through the IWbemLocator::ConnectServer method
    
        CComPtr<EventSink> pSink(new EventSink(callback));
    
        // Connect to the local root\cimv2 namespace
        // and obtain pointer pSvc to make IWbemServices calls.
        hres = pLoc->ConnectServer(
            _bstr_t(L"ROOT\\CIMV2"), 
            NULL,
            NULL, 
            0, 
            NULL, 
            0, 
            0, 
            &pSink->pSvc
            );
    
        if (FAILED(hres))
        {
            cout << "Could not connect. Error code = 0x" 
                << hex << hres << endl;
            throw std::exception("ProcessTerminationNotificaiton initialization failed");
        }
    
        // Step 5: --------------------------------------------------
        // Set security levels on the proxy -------------------------
    
        hres = CoSetProxyBlanket(
            pSink->pSvc,                        // Indicates the proxy to set
            RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx 
            RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx 
            NULL,                        // Server principal name 
            RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
            RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
            NULL,                        // client identity
            EOAC_NONE                    // proxy capabilities 
            );
    
        if (FAILED(hres))
        {
            cout << "Could not set proxy blanket. Error code = 0x" 
                << hex << hres << endl;
            throw std::exception("ProcessTerminationNotificaiton initialization failed");
        }
    
        // Step 6: -------------------------------------------------
        // Receive event notifications -----------------------------
    
        // Use an unsecured apartment for security
        CComPtr<IUnsecuredApartment> pUnsecApp;
    
        hres = CoCreateInstance(CLSID_UnsecuredApartment, NULL, 
            CLSCTX_LOCAL_SERVER, IID_IUnsecuredApartment, 
            (void**)&pUnsecApp);
    
        CComPtr<IUnknown> pStubUnk; 
        pUnsecApp->CreateObjectStub(pSink, &pStubUnk);
    
        pStubUnk->QueryInterface(IID_IWbemObjectSink,
            (void **) &pSink->pStubSink);
    
        // The ExecNotificationQueryAsync method will call
        // The EventQuery::Indicate method when an event occurs
        char buffer[512];
        sprintf_s(buffer, "SELECT * " 
            "FROM __InstanceDeletionEvent WITHIN 1 "
            "WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.ProcessId=%u", processId);
    
        hres = pSink->pSvc->ExecNotificationQueryAsync(
            _bstr_t("WQL"), 
            _bstr_t(buffer), 
            WBEM_FLAG_SEND_STATUS, 
            NULL, 
            pSink->pStubSink);
    
        // Check for errors.
        if (FAILED(hres))
        {
            cout << "ExecNotificationQueryAsync failed "
                "with = 0x" << hex << hres << endl;
            throw std::exception("ProcessTerminationNotificaiton initialization failed");
        }
    }
    0 0
相关问答

42

回答

[@徐雷frank][¥20]什么是JAVA的平台无关性

大河人家 2018-10-29 23:55:20 147540浏览量 回答数 42

170

回答

惊喜翻倍:免费ECS+免费环境配置~!(ECS免费体验6个月活动3月31日结束)

豆妹 2014-10-29 17:52:21 233967浏览量 回答数 170

8

回答

OceanBase 使用动画(持续更新)

mq4096 2019-02-20 17:16:36 341430浏览量 回答数 8

13

回答

[@饭娱咖啡][¥20]我想知道 Java 关于引用那一块的知识

心意乱 2018-10-31 18:44:12 143664浏览量 回答数 13

119

回答

OSS存储服务-客户端工具

newegg11 2012-05-17 15:37:18 302732浏览量 回答数 119

22

回答

爬虫数据管理【问答合集】

我是管理员 2018-08-10 16:37:41 149001浏览量 回答数 22

24

回答

阿里云开放端口权限

xcxx 2016-07-20 15:03:33 660689浏览量 回答数 24

31

回答

[@倚贤][¥20]刚学完html/css/js的新手学习servlet、jsp需要注意哪些问题?

弗洛伊德6 2018-10-27 21:52:43 148125浏览量 回答数 31

43

回答

【精品问答集锦】Python热门问题

小六码奴 2019-05-30 15:27:34 144693浏览量 回答数 43

10

回答

[@墨玖tao][¥20]为什么流式处理框架都是 java 写成的,JVM 是不是在流和批存在着特殊优势。还有分布式资源调度,感觉Mesos 的成长速度跟不上 Yarn。这是为什么?

管理贝贝 2018-10-23 13:18:03 137789浏览量 回答数 10
+关注
0
文章
14879
问答
问答排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载