
完整代码如下:
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);
}
}
}
}
本文介绍了一个使用C#编写的简单应用程序,该程序能够枚举当前系统中运行的所有进程并显示其名称,同时提供了终止指定进程的功能。通过调用Windows API函数实现进程快照的创建、遍历及关闭。
1179

被折叠的 条评论
为什么被折叠?



