如何在Windows中挂钩应用程序和进程启动?

tre*_*rog 5 windows hook

我正在尝试编写一个程序,它将挂钩到应用程序启动并捕获命令行.不知道从哪里开始,因为我在Windows编程中非常环保.非常感谢任何帮助谢谢

far*_*jad 6

你没有提到你喜欢的编程语言,所以我将使用 C# 作为示例片段。

您可以启动一个进程并捕获/写入其标准 IO 流。

以下代码段打开一个进程并捕获其StdOut流:

using (var process = Process.Start(new ProcessStartInfo(FileName = @"yourExecutablePath", UseShellExecute = false, RedirectStandardOutput = true)))
    using (var stdout = process.StandardOutput)
        Console.WriteLine(stdout.ReadToEnd());
Run Code Online (Sandbox Code Playgroud)

编辑 1

看起来您想挂钩 Windows API,例如CreateProcess

一种方法是编写内核驱动程序并使用钩子技术,例如 SSTD 补丁。但是编写内核驱动程序 IMO 很麻烦。

在某些情况下,您可以使用用户级挂钩。有一些库可以帮助您解决这个问题,包括:EasyHookDeviareMS Detour


编辑 2

您也可以按照建议使用WMI@David Heffernan但它只会在进程启动通知您(与挂钩相反,挂钩允许您在调用挂钩函数和/或覆盖函数调用之前运行一些任意代码):

using System.Management;

// Run this in another thread and make sure the event watcher gets disposed before exit

var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));    

start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
    console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
});

start.Start()
Run Code Online (Sandbox Code Playgroud)