一个windows防火墙管理器
下载地址:https://pan.quark.cn/s/15a680dd0cd0

Program.cs内容
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using NetFwTypeLib;
using FirewallManager;
namespace FirewallManager
{
public partial class MainForm : Form
{
private INetFwPolicy2 firewallPolicy;
private ListView listViewRules;
private Button btnAddRule;
private Button btnRemoveRule;
private Button btnRefresh;
private Button btnBrowseApp;
private Button btnListInvalidRules;
private Button btnCheckDuplicates;
private TextBox txtAppPath;
private TextBox txtRuleName;
private ComboBox cmbDirection;
private ComboBox cmbAction;
private GroupBox groupBoxAddRule;
private StatusStrip statusStrip;
private ToolStripStatusLabel statusLabel;
public MainForm()
{
InitializeComponent();
InitializeFirewall();
LoadFirewallRules();
// 处理窗口大小变化
this.Resize += MainForm_Resize;
// 添加双击事件处理
listViewRules.DoubleClick += ListViewRules_DoubleClick;
}
private void MainForm_Resize(object sender, EventArgs e)
{
// 调整ListView的大小
listViewRules.Size = new Size(this.ClientSize.Width - 24, this.ClientSize.Height - 200);
// 调整GroupBox的位置和大小
groupBoxAddRule.Location = new Point(12, this.ClientSize.Height - 180);
groupBoxAddRule.Size = new Size(this.ClientSize.Width - 24, 150);
// 调整程序路径输入框的宽度
txtAppPath.Size = new Size(this.ClientSize.Width - 200, 20);
// 调整浏览按钮的位置
btnBrowseApp.Location = new Point(this.ClientSize.Width - 120, 51);
}
private void InitializeComponent()
{
this.Text = "防火墙管理器";
this.Size = new Size(800, 600);
this.StartPosition = FormStartPosition.CenterScreen;
this.MinimumSize = new Size(600, 500);
// 创建ListView显示规则
listViewRules = new ListView();
listViewRules.Location = new Point(12, 12);
listViewRules.Size = new Size(760, 300);
listViewRules.View = View.Details;
listViewRules.FullRowSelect = true;
listViewRules.GridLines = true;
listViewRules.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
listViewRules.Columns.Add("规则名称", 200);
listViewRules.Columns.Add("程序路径", 300);
listViewRules.Columns.Add("方向", 80);
listViewRules.Columns.Add("动作", 80);
listViewRules.Columns.Add("启用", 60);
this.Controls.Add(listViewRules);
// 创建添加规则的GroupBox
groupBoxAddRule = new GroupBox();
groupBoxAddRule.Text = "添加新规则";
groupBoxAddRule.Location = new Point(12, 320);
groupBoxAddRule.Size = new Size(760, 150);
groupBoxAddRule.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
// 规则名称
Label lblRuleName = new Label();
lblRuleName.Text = "规则名称:";
lblRuleName.Location = new Point(10, 25);
lblRuleName.Size = new Size(70, 20);
groupBoxAddRule.Controls.Add(lblRuleName);
txtRuleName = new TextBox();
txtRuleName.Location = new Point(85, 22);
txtRuleName.Size = new Size(200, 20);
groupBoxAddRule.Controls.Add(txtRuleName);
// 程序路径
Label lblAppPath = new Label();
lblAppPath.Text = "程序路径:";
lblAppPath.Location = new Point(10, 55);
lblAppPath.Size = new Size(70, 20);
groupBoxAddRule.Controls.Add(lblAppPath);
txtAppPath = new TextBox();
txtAppPath.Location = new Point(85, 52);
txtAppPath.Size = new Size(400, 20);
txtAppPath.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
groupBoxAddRule.Controls.Add(txtAppPath);
btnBrowseApp = new Button();
btnBrowseApp.Text = "浏览...";
btnBrowseApp.Location = new Point(495, 51);
btnBrowseApp.Size = new Size(70, 22);
btnBrowseApp.Anchor = AnchorStyles.Top | AnchorStyles.Right;
btnBrowseApp.Click += BtnBrowseApp_Click;
groupBoxAddRule.Controls.Add(btnBrowseApp);
// 方向
Label lblDirection = new Label();
lblDirection.Text = "方向:";
lblDirection.Location = new Point(10, 85);
lblDirection.Size = new Size(70, 20);
groupBoxAddRule.Controls.Add(lblDirection);
cmbDirection = new ComboBox();
cmbDirection.Location = new Point(85, 82);
cmbDirection.Size = new Size(100, 20);
cmbDirection.DropDownStyle = ComboBoxStyle.DropDownList;
cmbDirection.Items.AddRange(new string[] { "入站", "出站" });
cmbDirection.SelectedIndex = 1; // 默认选择出站
groupBoxAddRule.Controls.Add(cmbDirection);
// 动作
Label lblAction = new Label();
lblAction.Text = "动作:";
lblAction.Location = new Point(200, 85);
lblAction.Size = new Size(50, 20);
groupBoxAddRule.Controls.Add(lblAction);
cmbAction = new ComboBox();
cmbAction.Location = new Point(255, 82);
cmbAction.Size = new Size(100, 20);
cmbAction.DropDownStyle = ComboBoxStyle.DropDownList;
cmbAction.Items.AddRange(new string[] { "允许", "阻止" });
cmbAction.SelectedIndex = 1; // 默认选择阻止
groupBoxAddRule.Controls.Add(cmbAction);
// 按钮
btnAddRule = new Button();
btnAddRule.Text = "添加规则";
btnAddRule.Location = new Point(10, 115);
btnAddRule.Size = new Size(80, 25);
btnAddRule.Click += BtnAddRule_Click;
groupBoxAddRule.Controls.Add(btnAddRule);
btnRemoveRule = new Button();
btnRemoveRule.Text = "删除规则";
btnRemoveRule.Location = new Point(100, 115);
btnRemoveRule.Size = new Size(80, 25);
btnRemoveRule.Click += BtnRemoveRule_Click;
groupBoxAddRule.Controls.Add(btnRemoveRule);
btnRefresh = new Button();
btnRefresh.Text = "刷新列表";
btnRefresh.Location = new Point(190, 115);
btnRefresh.Size = new Size(80, 25);
btnRefresh.Click += BtnRefresh_Click;
groupBoxAddRule.Controls.Add(btnRefresh);
btnListInvalidRules = new Button();
btnListInvalidRules.Text = "列出无效规则";
btnListInvalidRules.Location = new Point(280, 115);
btnListInvalidRules.Size = new Size(90, 25);
btnListInvalidRules.Click += BtnListInvalidRules_Click;
groupBoxAddRule.Controls.Add(btnListInvalidRules);
btnCheckDuplicates = new Button();
btnCheckDuplicates.Text = "检查重复规则";
btnCheckDuplicates.Location = new Point(380, 115);
btnCheckDuplicates.Size = new Size(90, 25);
btnCheckDuplicates.Click += BtnCheckDuplicates_Click;
groupBoxAddRule.Controls.Add(btnCheckDuplicates);
this.Controls.Add(groupBoxAddRule);
// 状态栏
statusStrip = new StatusStrip();
statusLabel = new ToolStripStatusLabel();
statusLabel.Text = "就绪 - 双击规则查看详细信息";
statusStrip.Items.Add(statusLabel);
this.Controls.Add(statusStrip);
}
private void InitializeFirewall()
{
try
{
firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
statusLabel.Text = "防火墙初始化成功";
}
catch (Exception ex)
{
MessageBox.Show($"初始化防火墙失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "防火墙初始化失败";
}
}
private void LoadFirewallRules()
{
try
{
listViewRules.Items.Clear();
// 定义需要过滤的系统关键进程
HashSet systemProcesses = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"svchost.exe",
"system",
"winlogon.exe",
"csrss.exe",
"smss.exe",
"wininit.exe",
"services.exe",
"lsass.exe",
"dwm.exe",
"explorer.exe",
"spoolsv.exe",
"conhost.exe",
"dllhost.exe",
"rundll32.exe",
"taskhost.exe",
"taskhostw.exe"
};
foreach (INetFwRule rule in firewallPolicy.Rules)
{
// 只显示应用程序规则
if (!string.IsNullOrEmpty(rule.ApplicationName))
{
string appName = Path.GetFileName(rule.ApplicationName);
// 过滤掉系统关键进程
if (systemProcesses.Contains(appName))
{
continue;
}
// 过滤掉Windows系统路径下的程序
string appPath = rule.ApplicationName.ToLower();
if (appPath.Contains("\\windows\\system32\\") ||
appPath.Contains("\\windows\\syswow64\\") ||
appPath.Contains("\\windows\\winsxs\\"))
{
continue;
}
ListViewItem item = new ListViewItem(rule.Name);
item.SubItems.Add(rule.ApplicationName);
item.SubItems.Add(rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? "入站" : "出站");
item.SubItems.Add(rule.Action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW ? "允许" : "阻止");
item.SubItems.Add(rule.Enabled ? "是" : "否");
item.Tag = rule;
listViewRules.Items.Add(item);
}
}
statusLabel.Text = $"已加载 {listViewRules.Items.Count} 条用户程序规则(已过滤系统进程)";
}
catch (Exception ex)
{
MessageBox.Show($"加载防火墙规则失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "加载规则失败";
}
}
private void BtnBrowseApp_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
openFileDialog.Title = "选择要管理的程序";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtAppPath.Text = openFileDialog.FileName;
if (string.IsNullOrEmpty(txtRuleName.Text))
{
txtRuleName.Text = Path.GetFileNameWithoutExtension(openFileDialog.FileName) + "_阻止";
}
}
}
private void BtnAddRule_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtRuleName.Text) || string.IsNullOrEmpty(txtAppPath.Text))
{
MessageBox.Show("请填写规则名称和程序路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (!File.Exists(txtAppPath.Text))
{
MessageBox.Show("指定的程序文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// 检查是否为系统关键进程
string appName = Path.GetFileName(txtAppPath.Text);
HashSet systemProcesses = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"svchost.exe", "system", "winlogon.exe", "csrss.exe", "smss.exe",
"wininit.exe", "services.exe", "lsass.exe", "dwm.exe", "explorer.exe"
};
if (systemProcesses.Contains(appName))
{
MessageBox.Show("不能对系统关键进程创建阻止规则,这可能导致系统不稳定!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// 检查是否为Windows系统路径
string appPath = txtAppPath.Text.ToLower();
if (appPath.Contains("\\windows\\system32\\") ||
appPath.Contains("\\windows\\syswow64\\") ||
appPath.Contains("\\windows\\winsxs\\"))
{
DialogResult result = MessageBox.Show("您正在为Windows系统目录下的程序创建规则,这可能影响系统功能。\n确定要继续吗?",
"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
return;
}
}
try
{
// 创建新的防火墙规则
INetFwRule newRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
newRule.Name = txtRuleName.Text;
newRule.ApplicationName = txtAppPath.Text;
newRule.Direction = cmbDirection.SelectedIndex == 0 ?
NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN :
NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
newRule.Action = cmbAction.SelectedIndex == 0 ?
NET_FW_ACTION_.NET_FW_ACTION_ALLOW :
NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
newRule.Enabled = true;
// 添加规则到防火墙
firewallPolicy.Rules.Add(newRule);
// 清空输入框
txtRuleName.Clear();
txtAppPath.Clear();
// 刷新列表
LoadFirewallRules();
MessageBox.Show("规则添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
statusLabel.Text = "规则添加成功";
}
catch (Exception ex)
{
MessageBox.Show($"添加规则失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "添加规则失败";
}
}
private void BtnRemoveRule_Click(object sender, EventArgs e)
{
if (listViewRules.SelectedItems.Count == 0)
{
MessageBox.Show("请选择要删除的规则", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (MessageBox.Show("确定要删除选中的规则吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
foreach (ListViewItem selectedItem in listViewRules.SelectedItems)
{
INetFwRule rule = (INetFwRule)selectedItem.Tag;
firewallPolicy.Rules.Remove(rule.Name);
}
LoadFirewallRules();
MessageBox.Show("规则删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
statusLabel.Text = "规则删除成功";
}
catch (Exception ex)
{
MessageBox.Show($"删除规则失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "删除规则失败";
}
}
}
private void BtnRefresh_Click(object sender, EventArgs e)
{
LoadFirewallRules();
}
private void BtnListInvalidRules_Click(object sender, EventArgs e)
{
try
{
listViewRules.Items.Clear();
int invalidCount = 0;
statusLabel.Text = "正在检查无效规则...";
Application.DoEvents(); // 更新UI显示
// 定义需要过滤的系统关键进程
HashSet systemProcesses = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"svchost.exe", "system", "winlogon.exe", "csrss.exe", "smss.exe",
"wininit.exe", "services.exe", "lsass.exe", "dwm.exe", "explorer.exe",
"spoolsv.exe", "conhost.exe", "dllhost.exe", "rundll32.exe",
"taskhost.exe", "taskhostw.exe"
};
foreach (INetFwRule rule in firewallPolicy.Rules)
{
// 只检查应用程序规则
if (!string.IsNullOrEmpty(rule.ApplicationName))
{
string appName = Path.GetFileName(rule.ApplicationName);
// 过滤掉系统关键进程
if (systemProcesses.Contains(appName))
{
continue;
}
// 过滤掉Windows系统路径下的程序
string appPath = rule.ApplicationName.ToLower();
if (appPath.Contains("\\windows\\system32\\") ||
appPath.Contains("\\windows\\syswow64\\") ||
appPath.Contains("\\windows\\winsxs\\"))
{
continue;
}
// 检查程序文件是否存在
if (!File.Exists(rule.ApplicationName))
{
invalidCount++;
ListViewItem item = new ListViewItem(rule.Name);
item.SubItems.Add(rule.ApplicationName);
item.SubItems.Add(rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? "入站" : "出站");
item.SubItems.Add(rule.Action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW ? "允许" : "阻止");
item.SubItems.Add(rule.Enabled ? "是" : "否");
item.Tag = rule;
// 将无效规则标记为红色
item.ForeColor = Color.Red;
item.Font = new Font(item.Font, FontStyle.Italic);
listViewRules.Items.Add(item);
}
}
}
if (invalidCount == 0)
{
statusLabel.Text = "未找到无效规则";
MessageBox.Show("未找到无效规则,所有规则的程序路径都存在。", "检查完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
statusLabel.Text = $"找到 {invalidCount} 条无效规则(程序文件不存在)";
MessageBox.Show($"找到 {invalidCount} 条无效规则,这些规则的程序文件已不存在。\n" +
"建议删除这些无效规则以保持防火墙配置的整洁。",
"检查完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show($"检查无效规则时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "检查无效规则失败";
}
}
private void BtnCheckDuplicates_Click(object sender, EventArgs e)
{
try
{
listViewRules.Items.Clear();
statusLabel.Text = "正在检查重复规则...";
Application.DoEvents(); // 更新UI显示
// 定义需要过滤的系统关键进程
HashSet systemProcesses = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"svchost.exe", "system", "winlogon.exe", "csrss.exe", "smss.exe",
"wininit.exe", "services.exe", "lsass.exe", "dwm.exe", "explorer.exe",
"spoolsv.exe", "conhost.exe", "dllhost.exe", "rundll32.exe",
"taskhost.exe", "taskhostw.exe"
};
// 用于存储规则的字典,key为规则特征,value为规则列表
Dictionary<string, List> ruleGroups = new Dictionary<string, List>();
foreach (INetFwRule rule in firewallPolicy.Rules)
{
// 只检查应用程序规则
if (!string.IsNullOrEmpty(rule.ApplicationName))
{
string appName = Path.GetFileName(rule.ApplicationName);
// 过滤掉系统关键进程
if (systemProcesses.Contains(appName))
{
continue;
}
// 过滤掉Windows系统路径下的程序
string appPath = rule.ApplicationName.ToLower();
if (appPath.Contains("\\windows\\system32\\") ||
appPath.Contains("\\windows\\syswow64\\") ||
appPath.Contains("\\windows\\winsxs\\"))
{
continue;
}
// 创建规则特征字符串(应用程序路径 + 方向 + 动作)
string ruleSignature = $"{rule.ApplicationName}|{rule.Direction}|{rule.Action}";
if (!ruleGroups.ContainsKey(ruleSignature))
{
ruleGroups[ruleSignature] = new List();
}
ruleGroups[ruleSignature].Add(rule);
}
}
// 找出重复的规则组
int duplicateCount = 0;
foreach (var group in ruleGroups)
{
if (group.Value.Count > 1) // 有重复
{
// 为每个重复的规则组添加一个分组标识
for (int i = 0; i < group.Value.Count; i++)
{
var rule = group.Value[i];
duplicateCount++;
ListViewItem item = new ListViewItem($"[重复{duplicateCount}] {rule.Name}");
item.SubItems.Add(rule.ApplicationName);
item.SubItems.Add(rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? "入站" : "出站");
item.SubItems.Add(rule.Action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW ? "允许" : "阻止");
item.SubItems.Add(rule.Enabled ? "是" : "否");
item.Tag = rule;
// 将重复规则标记为橙色
item.ForeColor = Color.Orange;
item.Font = new Font(item.Font, FontStyle.Bold);
// 如果不是第一个,用更深的颜色标识
if (i > 0)
{
item.ForeColor = Color.Red;
}
listViewRules.Items.Add(item);
}
// 添加一个空行分隔不同的重复组
if (duplicateCount > 0)
{
ListViewItem separator = new ListViewItem("──────────────────");
separator.ForeColor = Color.Gray;
listViewRules.Items.Add(separator);
}
}
}
if (duplicateCount == 0)
{
statusLabel.Text = "未找到重复规则";
MessageBox.Show("未找到重复规则,所有规则的程序路径、方向、动作组合都是唯一的。", "检查完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
statusLabel.Text = $"找到 {duplicateCount} 条可能重复的规则";
MessageBox.Show($"找到 {duplicateCount} 条可能重复的规则。\n\n" +
"注意:这些规则的程序路径、方向、动作相同,但可能在端口、协议等其他属性上有差异。\n" +
"建议仔细检查后再决定是否删除。橙色为重复组的第一个规则,红色为后续重复规则。",
"检查完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show($"检查重复规则时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
statusLabel.Text = "检查重复规则失败";
}
}
private void ListViewRules_DoubleClick(object sender, EventArgs e)
{
if (listViewRules.SelectedItems.Count == 0)
return;
ListViewItem selectedItem = listViewRules.SelectedItems[0];
INetFwRule rule = selectedItem.Tag as INetFwRule;
if (rule == null)
return;
ShowRuleDetails(rule);
}
private void ShowRuleDetails(INetFwRule rule)
{
try
{
StringBuilder details = new StringBuilder();
details.AppendLine($"规则名称: {rule.Name}");
details.AppendLine($"描述: {rule.Description ?? "无"}");
details.AppendLine($"应用程序路径: {rule.ApplicationName}");
details.AppendLine();
// 基本属性
details.AppendLine("=== 基本属性 ===");
details.AppendLine($"方向: {(rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? "入站" : "出站")}");
details.AppendLine($"动作: {(rule.Action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW ? "允许" : "阻止")}");
details.AppendLine($"启用状态: {(rule.Enabled ? "已启用" : "已禁用")}");
details.AppendLine($"配置文件: {GetProfileString(rule.Profiles)}");
details.AppendLine();
// 协议和端口
details.AppendLine("=== 协议和端口 ===");
details.AppendLine($"协议: {GetProtocolString(rule.Protocol)}");
if (rule.Protocol == 6 || rule.Protocol == 17) // TCP或UDP
{
details.AppendLine($"本地端口: {rule.LocalPorts ?? "任意"}");
details.AppendLine($"远程端口: {rule.RemotePorts ?? "任意"}");
}
else if (rule.Protocol == 1) // ICMP
{
details.AppendLine($"ICMP类型和代码: {rule.IcmpTypesAndCodes ?? "任意"}");
}
details.AppendLine();
// IP地址
details.AppendLine("=== IP地址 ===");
details.AppendLine($"本地地址: {rule.LocalAddresses ?? "任意"}");
details.AppendLine($"远程地址: {rule.RemoteAddresses ?? "任意"}");
details.AppendLine();
// 高级属性
details.AppendLine("=== 高级属性 ===");
details.AppendLine($"边缘遍历: {(rule.EdgeTraversal ? "允许" : "不允许")}");
details.AppendLine($"接口类型: {rule.InterfaceTypes ?? "所有"}");
details.AppendLine($"分组: {rule.Grouping ?? "无"}");
// 显示详细信息对话框
Form detailForm = new Form();
detailForm.Text = $"规则详细信息 - {rule.Name}";
detailForm.Size = new Size(600, 500);
detailForm.StartPosition = FormStartPosition.CenterParent;
detailForm.MaximizeBox = false;
detailForm.MinimizeBox = false;
detailForm.FormBorderStyle = FormBorderStyle.FixedDialog;
TextBox textBox = new TextBox();
textBox.Multiline = true;
textBox.ReadOnly = true;
textBox.ScrollBars = ScrollBars.Vertical;
textBox.Font = new Font("Consolas", 9);
textBox.Text = details.ToString();
textBox.Dock = DockStyle.Fill;
textBox.Margin = new Padding(10);
Panel panel = new Panel();
panel.Dock = DockStyle.Fill;
panel.Padding = new Padding(10);
panel.Controls.Add(textBox);
Button closeButton = new Button();
closeButton.Text = "关闭";
closeButton.Size = new Size(80, 30);
closeButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
closeButton.Location = new Point(detailForm.Width - 100, detailForm.Height - 70);
closeButton.Click += (s, e) => detailForm.Close();
detailForm.Controls.Add(panel);
detailForm.Controls.Add(closeButton);
detailForm.ShowDialog(this);
}
catch (Exception ex)
{
MessageBox.Show($"显示规则详细信息时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private string GetProtocolString(int protocol)
{
switch (protocol)
{
case 1: return "ICMP";
case 2: return "IGMP";
case 6: return "TCP";
case 17: return "UDP";
case 58: return "ICMPv6";
case 256: return "任意";
default: return $"协议号 {protocol}";
}
}
private string GetProfileString(int profiles)
{
List profileList = new List();
if ((profiles & 1) != 0) profileList.Add("域");
if ((profiles & 2) != 0) profileList.Add("专用");
if ((profiles & 4) != 0) profileList.Add("公用");
return profileList.Count > 0 ? string.Join(", ", profileList) : "所有";
}
}
}
// 程序入口点
public class Program
{
[STAThread]
static void Main()
{
// 检查是否以管理员身份运行
if (!IsRunAsAdmin())
{
// 尝试以管理员身份重新启动程序
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas"; // 请求管理员权限
Process.Start(startInfo);
return; // 退出当前进程
}
catch (Exception ex)
{
MessageBox.Show($"获取管理员权限失败: {ex.Message}\n\n" +
"此程序需要管理员权限才能管理防火墙规则。\n" +
"请右键点击程序选择'以管理员身份运行'。",
"需要管理员权限", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
private static bool IsRunAsAdmin()
{
try
{
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
}
浙公网安备 33010602011771号