完整代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x100)]
public string szExeFile;
}
[DllImport("Kernel32.dll")]
private static extern int CloseToolhelp32Snapshot(IntPtr snaph);
[DllImport("Kernel32.dll")]
private static extern int CloseHandle(IntPtr hObject);
[DllImport("Kernel32.dll")]
private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("Kernel32.dll")]
private static extern int Process32First(int snaph, ref PROCESSENTRY32 lppe);
[DllImport("Kernel32.dll")]
private static extern int Process32Next(IntPtr snaph, ref PROCESSENTRY32 lppe);
[DllImport("Kernel32.dll")]
private static extern bool TerminateProcess(IntPtr h, uint c);
private void button1_Click(object sender, EventArgs e)
{
IntPtr snaph = CreateToolhelp32Snapshot(2, 0);
PROCESSENTRY32 lppe = new PROCESSENTRY32();
lppe.dwSize = 0x400;
if (Process32First((int)snaph, ref lppe) == 0)
{
CloseToolhelp32Snapshot(snaph);
}
while (Process32Next(snaph, ref lppe) != 0)
{
this.listBox1.Items.Add(lppe.szExeFile);
}
}
}
}