如何检测进程启动&结束在 Windows 中使用 c#? [英] How to detect a process start & end using c# in windows?

查看:21
本文介绍了如何检测进程启动&结束在 Windows 中使用 c#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 方面有很好的工作经验,但现在我想开发一个简单的(可能是控制台应用程序)软件,它只检测我计算机上开始或结束的进程的名称和时间.

I have a good working experience with C# but now I want to develop a simple(may be a console app) software which just detects the name and time of the process started or ended on my computer.

例如(我假设我的小应用程序已经在运行)如果用户打开 Firefox,那么它应该随时间将 firefox.exe 插入到数据库中,如果用户关闭它,它也会执行相同的操作.

For example (I am assuming that my small app is already running) if a user opens Firefox then it should just insert firefox.exe into a database with time and if a user close it then it also do the same.

和上面一样,如果用户打开记​​事本,那么它应该插入带有时间等的notepad.exe.

And same as above if a user open notepad then it should insert notepad.exe with time and so on.

我知道如何在数据库中插入值,但我只需要您的帮助来确定进程/程序何时在我的系统上启动或结束.

I know how to insert values in database but I just need your help in identifying when the process/program starts or ends on my system.

老实说我以前从未开发过这种应用程序,所以我不知道可以使用控制台应用程序还是我需要制作 Windows 服务应用程序等.

Honestly saying I never developed this kind of application before so i have no idea that it can be possible using console app or i need to make a windows service app etc.

所以请仅将我视为初学者来提供您的答案.

So please provide your answer just considering me as a beginner.

在 C# 部分,我能够理解它,所以需要担心.

In the part of C# I am able to understand it so need to worry about that.

我使用的是带有 .net 4.0 的 Visual Studio 2010.

I am using visual studio 2010 with .net 4.0.

推荐答案

要在没有轮询的情况下执行此操作,需要 WMI.这在 .net 中得到了很好的支持,您可以使用 ManagementEventWatcher 类订阅 WMI 通知.

To do this without polling requires WMI. This is well supported in .net and you can use the ManagementEventWatcher class to subscribe to WMI notifications.

这篇代码项目文章说明了如何它完成了.这是一段摘录,显示了它是多么简单.

This Code Project article illustrates how it is done. Here's an extract showing how straightforward it is.

notePad = new ProcessInfo("notepad.exe");
notePad.Started +=
    new Win32Process.ProcessInfo.StartedEventHandler(this.NotepadStarted);
notePad.Terminated +=
    new Win32Process.ProcessInfo.TerminatedEventHandler(this.NotepadTerminated);

请注意,ProcessInfo 是该文章所附代码中实现的类.

Note that ProcessInfo is a class implemented in the code attached to that article.

这篇关于如何检测进程启动&结束在 Windows 中使用 c#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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