csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace NetworkMonitor
{
public partial class MainForm : Form
{
// 定义TCP状态
public enum TCP_TABLE_CLASS
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
// 定义用于存储TCP连接信息的结构
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
// 后续为MIB_TCPROW_OWNER_PID,这里简化
}
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern uint GetExtendedTcpTable(
IntPtr pTcpTable,
ref int dwOutBufLen,
bool sort,
int ipVersion,
TCP_TABLE_CLASS tblClass,
uint reserved);
private Dictionary<int, ProcessNetworkData> processNetworkData = new Dictionary<int, ProcessNetworkData>();
private Timer updateTimer;
public MainForm()
{
InitializeComponent();
InitializeListView();
InitializeComboBox();
StartMonitoring();
}
private void InitializeListView()
{
listView1.View = View.Details;
listView1.Columns.Add("进程名称", 150);
listView1.Columns.Add("下载速度 (KB/s)", 120);
listView1.Columns.Add("上传速度 (KB/s)", 120);
listView1.Columns.Add("下载累计 (MB)", 120);
listView1.Columns.Add("上传累计 (MB)", 120);
}
private void InitializeComboBox()
{
comboBox1.Items.Add("按下载速度排序");
comboBox1.Items.Add("按程序名称排序");
comboBox1.SelectedIndex = 0;
comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
}
private void StartMonitoring()
{
updateTimer = new Timer(UpdateNetworkData, null, 0, 1000); // 每秒更新一次
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
RefreshListView();
}
private void UpdateNetworkData(object state)
{
// 获取当前所有TCP连接
var connections = GetAllTcpConnections();
// 清当前快照
var currentProcesses = new Dictionary<int, ProcessNetworkData>();
foreach (var conn in connections)
{
if (!currentProcesses.ContainsKey(conn.ProcessId))
{
try
{
var process = Process.GetProcessById(conn.ProcessId);
currentProcesses[conn.ProcessId] = new ProcessNetworkData
{
ProcessId = conn.ProcessId,
ProcessName = process.ProcessName,
BytesSent = 0,
BytesReceived = 0,
TotalBytesSent = 0,
TotalBytesReceived = 0
};
}
catch
{
// 进程可能已退出,忽略
continue;
}
}
// 这里需要实际获取这个连接的上传和下载字节数,这部分需要更复杂的网络包捕获或其他方法
// 这里为了示例,我们假设每个连接每秒传输1KB
currentProcesses[conn.ProcessId].BytesSent += 1024; // 上传速度
currentProcesses[conn.ProcessId].BytesReceived += 1024; // 下载速度
}
// 更新累计流量
foreach (var proc in currentProcesses.Values)
{
if (!processNetworkData.ContainsKey(proc.ProcessId))
{
processNetworkData[proc.ProcessId] = proc;
}
else
{
processNetworkData[proc.ProcessId].BytesSent = proc.BytesSent;
processNetworkData[proc.ProcessId].BytesReceived = proc.BytesReceived;
processNetworkData[proc.ProcessId].TotalBytesSent += proc.BytesSent;
processNetworkData[proc.ProcessId].TotalBytesReceived += proc.BytesReceived;
}
}
// 移除没有流量的进程
var keysToRemove = new List<int>();
foreach (var kvp in processNetworkData)
{
if (!currentProcesses.ContainsKey(kvp.Key))
{
if (kvp.Value.BytesSent == 0 && kvp.Value.BytesReceived == 0)
{
keysToRemove.Add(kvp.Key);
}
}
}
foreach (var key in keysToRemove)
{
processNetworkData.Remove(key);
}
// 刷新UI
this.Invoke(new Action(() => RefreshListView()));
}
private void RefreshListView()
{
listView1.BeginUpdate();
listView1.Items.Clear();
List<ProcessNetworkData> displayList = new List<ProcessNetworkData>();
foreach (var data in processNetworkData.Values)
{
if (data.BytesSent > 0 || data.BytesReceived > 0 || data.TotalBytesSent > 0 || data.TotalBytesReceived > 0)
{
displayList.Add(data);
}
}
// 排序
if (comboBox1.SelectedIndex == 0)
{
// 按下载速度排序
displayList.Sort((a, b) => b.BytesReceived.CompareTo(a.BytesReceived));
}
else
{
// 按进程名称排序
displayList.Sort((a, b) => a.ProcessName.CompareTo(b.ProcessName));
}
// 添加到ListView
foreach (var data in displayList)
{
var item = new ListViewItem(data.ProcessName);
item.SubItems.Add((data.BytesReceived / 1024.0).ToString("F2"));
item.SubItems.Add((data.BytesSent / 1024.0).ToString("F2"));
item.SubItems.Add((data.TotalBytesReceived / (1024.0 * 1024)).ToString("F2"));
item.SubItems.Add((data.TotalBytesSent / (1024.0 * 1024)).ToString("F2"));
listView1.Items.Add(item);
}
listView1.EndUpdate();
}
private List<TcpConnection> GetAllTcpConnections()
{
List<TcpConnection> connections = new List<TcpConnection>();
// 这里需要实现通过GetExtendedTcpTable获取所有TCP连接,并关联到进程ID
// 为了简化示例,这里返回一个空列表
return connections;
}
}
public class ProcessNetworkData
{
public int ProcessId { get; set; }
public string ProcessName { get; set; }
public long BytesSent { get; set; } // 当前上传速度
public long BytesReceived { get; set; } // 当前下载速度
public long TotalBytesSent { get; set; } // 累计上传
public long TotalBytesReceived { get; set; } // 累计下载
}
public struct TcpConnection
{
public string LocalAddress;
public string RemoteAddress;
public int LocalPort;
public int RemotePort;
public int ProcessId;
}
}