2014-12-05 103 views
5

我試圖在使用Delphi XE3的Windows 7上管理防火牆規則(例外)。我發現了一個非常有趣的向Windows防火牆添加規則的代碼,但是沒有關於刪除(刪除)的規則。請有人幫忙嗎?使用Delphi刪除Windows防火牆規則(例外)

這裏是代碼添加規則:

procedure AddExceptToFirewall(const Caption, AppPath: String); 
// Uses ComObj 
const 
    NET_FW_PROFILE2_PRIVATE = 2; 
    NET_FW_PROFILE2_PUBLIC = 4; 
    NET_FW_IP_PROTOCOL_TCP = 6; 
    NET_FW_ACTION_ALLOW  = 1; 
var 
    Profile: Integer; 
    Policy2: OleVariant; 
    RObject: OleVariant; 
    NewRule: OleVariant; 
begin 
    Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC; 
    Policy2 := CreateOleObject('HNetCfg.FwPolicy2'); 
    RObject := Policy2.Rules; 
    NewRule := CreateOleObject('HNetCfg.FWRule'); 
    NewRule.Name  := Caption; 
    NewRule.Description := Caption; 
    NewRule.ApplicationName := AppPath; 
    NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP; 
    NewRule.Enabled := True; 
    NewRule.Grouping := ''; 
    NewRule.Profiles := Profile; 
    NewRule.Action := NET_FW_ACTION_ALLOW; 
    RObject.Add(NewRule); 
end; 

謝謝!

回答

5

您只需撥打INetFWRules.Remove,傳遞規則的名稱。名稱與創建時使用的名稱相同(RObject.Name在您上面提供的代碼中)。

// Note: Normal COM exception handling should be used. Omitted for clarity. 

procedure RemoveExceptFromFirewall(const RuleName: String); 
const 
    NET_FW_PROFILE2_PRIVATE = 2; 
    NET_FW_PROFILE2_PUBLIC = 4; 
var 
    Profile: Integer; 
    Policy2: OleVariant; 
    RObject: OleVariant; 
begin 
    Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC; 
    Policy2 := CreateOleObject('HNetCfg.FwPolicy2'); 
    RObject := Policy2.Rules; 
    RObject.Remove(RuleName); 
end; 

在鏈接文檔中幾乎沒有提供任何內容,BTW。我提供的鏈接僅供參考。

+0

謝謝@Ken White!我以前沒有找到任何地方... – Guybrush 2014-12-05 20:23:47

+1

@Paruba,你應該考慮導入類型庫,而不是從網上覆制晚期綁定代碼。另外,你應該從方法調用中檢查'HRESULT'。這兩個建議可以爲您節省很多麻煩。 – 2014-12-05 23:47:12

+1

僅供參考,防火牆API的TypeLibrary位於'%WINDIR%\ System32 \ FirewallAPI.dll'中。 – 2014-12-06 01:40:48

相關問題