首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

程式化管理 Windows 防火牆:允許/封鎖應用程式完整範例

     編輯:關於C語言

應用場景

安裝程式或管理工具常需自動將應用程式加入 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)
ModeENABLE 允許 / DISABLE 封鎖
Scope範圍:LocalSubnet、All 等
Address自訂 IP 範圍(CIDR),Scope 為 Custom 時生效

注意事項

  • 需參考 NetFwTypeLib (FirewallAPI.dll),或使用 INetFwPolicy2 介面 (Vista+)。
  • 執行需管理員權限(UAC 提升),否則 Set() 會拋出存取拒絕例外。
  • 建議封裝為獨立元件,提供非同步版本避免 UI 凍結。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved