安裝程式或管理工具常需自動將應用程式加入 Windows 防火牆允許清單,或根據使用者設定啟用/停用規則。本文展示透過 NetFwTypeLib (COM 元件) 封裝的 AllowedProgram 類別完整呼叫範例。
private void btnAllow_Click(object sender, EventArgs e)
{
try
{
var ap = new AllowedProgram
{
Program = txtPath.Text.Trim(),
Mode = chkEnable.Checked ? TMode.ENABLE : TMode.DISABLE,
Scope = (TScope)cboScope.SelectedItem,
Address = txtAddress.Text.Trim()
};
ap.Set(); // 寫入防火牆規則
MessageBox.Show("設定成功", "資訊");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
var ap = new AllowedProgram { Program = txtPath.Text.Trim() };
ap.Delete(); // 移除規則
MessageBox.Show("刪除成功", "資訊");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
| 屬性 | 說明 |
|---|---|
| Program | 應用程式完整路徑(.exe) |
| Mode | ENABLE 允許 / DISABLE 封鎖 |
| Scope | 範圍:LocalSubnet、All 等 |
| Address | 自訂 IP 範圍(CIDR),Scope 為 Custom 時生效 |
NetFwTypeLib (FirewallAPI.dll),或使用 INetFwPolicy2 介面 (Vista+)。Set() 會拋出存取拒絕例外。