Jump to content
Bilgus

Windows Firewall Policy2 Interface UDF, Provides access to the firewall policy for Windows Vista+

Recommended Posts

; NetFirewallPolicy2 COM UDF Library for AutoIt3
; AutoIt Version : 3.3.14.5
; Description ...: Windows Firewall Policy2 Interface, Provides access to the firewall policy for Windows Vista+

Including Test Script 

  • _NetFw_Get_CurrentProfileTypes                           Retrieves the currently active firewall profile(s)
  • _NetFw_Get_FirewallEnabled                               Indicates whether a firewall is enabled locally
  • _NetFw_Put_FirewallEnabled                               Specifies whether a firewall is enabled locally
  • _NetFw_Get_ExcludedInterfaces                            Indicates a list of interfaces on which firewall settings are excluded
  • _NetFw_Put_ExcludedInterfaces                            Specifies a list of interfaces on which firewall settings are excluded
  • _NetFw_Get_BlockAllInboundTraffic                        Indicates whether the firewall should not allow inbound traffic
  • _NetFw_Put_BlockAllInboundTraffic                        Specifies whether the firewall should not allow inbound traffic
  • _NetFw_Get_NotificationsDisabled                         Indicates whether interactive firewall notifications are disabled
  • _NetFw_Put_NotificationsDisabled                         Specifies whether interactive firewall notifications are disabled
  • _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled  Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
  • _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled  Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
  • _NetFw_Get_Rules                                         Retrieves the interface to collection of firewall rules
  • _NetFw_Get_ServiceRestriction                            Retrieves the interface used to access the Windows Service Hardening store
  • _NetFw_EnableRuleGroup                                   Enables or disables a specified group of firewall rules
  • _NetFw_IsRuleGroupEnabled                                Determines whether a specified group of firewall rules are enabled or disabled for the current profile
  • _NetFw_RestoreLocalFirewallDefaults                      Restores the local firewall configuration to its default state
  • _NetFw_Get_DefaultInboundAction                          Indicates the default action for inbound traffic
  • _NetFw_Put_DefaultInboundAction                          Specifies the default action for inbound traffic
  • _NetFw_Get_DefaultOutboundAction                         Indicates the default action for outbound traffic
  • _NetFw_Put_DefaultOutboundAction                         Specifies the default action for outbound traffic
  • _NetFw_Get_IsRuleGroupCurrentlyEnabled                   Determines whether a specified group of firewall rules are enabled or disabled for the current profile
  • _NetFw_Get_LocalPolicyModifyState                        Determines if adding or setting a rule or group of rules will take effect in the current firewall profile

 

UDF:

Spoiler
;INetFwPolicy2COM.au3
#include-once
;#RequireAdmin

#include <WinAPIConstants.au3> ; $S_OK, $E_NOINTERFACE, $E_NOTIMPL
#include <WinAPIMisc.au3> ; _WinAPI_GetString


; #INDEX# ========================================================================================================================================================================
; Title .........: NetFirewallPolicy2 COM UDF Library for AutoIt3
; AutoIt Version : 3.3.14.5
; Description ...: Windows Firewall Policy2 Interface, Provides access to the firewall policy for Windows Vista+
; Author(s) .....: Bilgus 2018
; ================================================================================================================================================================================
#Region Global Variables and Constants
Global $__g_oINetFwPolicy2

; #CONSTANTS# ====================================================================================================================================================================
Global Enum $NET_FW_PROFILE2_DOMAIN = 0x1, $NET_FW_PROFILE2_PRIVATE = 0x2, $NET_FW_PROFILE2_PUBLIC = 0x4, $NET_FW_PROFILE2_ALL = 0x7FFFFFFF
Global Enum $NET_FW_MODIFY_STATE_OK = 0x0, $NET_FW_MODIFY_STATE_GP_OVERRIDE, $NET_FW_MODIFY_STATE_INBOUND_BLOCKED
Global Enum $NET_FW_ACTION_BLOCK = 0x0, $NET_FW_ACTION_ALLOW, $NET_FW_ACTION_MAX

; #INTERNAL CONSTANTS#============================================================================================================================================================
Global Enum $NET_FW_VARIANT_TRUE = -1, $NET_FW_VARIANT_FALSE = False ;A value 0 will be equal to Boolean False, Any other number value will be equal to Boolean True
Global Enum $NET_FW_VT_VARIANT = 0x000C, $NET_FW_VT_ARRAY = 0x2000, $NET_FW_VT_BSTR = 0x0008
Global Const $NET_FW_UNKNOWNERROR = 0xE

Global Const $dtag_INetFwPolicy2 = _ ; Inherits from IDispatch.
        "GetTypeInfoCount hresult(dword*);" & _ ; Retrieves the number of type information interfaces that an object provides (either 0 or 1).
        "GetTypeInfo hresult(dword;dword;ptr*);" & _ ; Gets the type information for an object.
        "GetIDsOfNames hresult(ptr;ptr;dword;dword;ptr);" & _ ; Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs, which can be used on subsequent calls to Invoke.
        "Invoke hresult(dword;ptr;dword;word;ptr;ptr;ptr;ptr);" & _ ; Provides access to properties and methods exposed by an object.
        "" & _ ;Endof IDispatch
        "get_CurrentProfileTypes          hresult(long*;);" & _ ;Retrieves the currently active firewall profile(s)
        "get_FirewallEnabled              hresult(int;short*);" & _ ;Indicates whether a firewall is enabled locally
        "put_FirewallEnabled              hresult(int;short);" & _ ;Specifies whether a firewall is enabled locally
        "get_ExcludedInterfaces           hresult(int;ptr);" & _ ;Indicates a list of interfaces on which firewall settings are excluded
        "put_ExcludedInterfaces           hresult(int;ptr);" & _ ;Specifies a list of interfaces on which firewall settings are excluded
        "get_BlockAllInboundTraffic       hresult(int;short*);" & _ ;Indicates whether the firewall should not allow inbound traffic
        "put_BlockAllInboundTraffic       hresult(int;short);" & _ ;Specifies whether the firewall should not allow inbound traffic
        "get_NotificationsDisabled        hresult(int;short*);" & _ ;Indicates whether interactive firewall notifications are disabled
        "put_NotificationsDisabled        hresult(int;short);" & _ ;Specifies whether interactive firewall notifications are disabled
        "get_UnicastResponsesToMulticastBroadcastDisabled        hresult(int;short*);" & _ ;Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
        "put_UnicastResponsesToMulticastBroadcastDisabled        hresult(int;short);" & _ ;Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
        "get_Rules                        hresult(ptr);" & _ ;Retrieves the interface to collection of firewall rules
        "get_ServiceRestriction           hresult(ptr);" & _ ;Retrieves the interface used to access the Windows Service Hardening store
        "EnableRuleGroup                  hresult(long;wstr;short);" & _ ;Enables or disables a specified group of firewall rules
        "IsRuleGroupEnabled               hresult(long;wstr;short*);" & _ ;Determines whether a specified group of firewall rules are enabled or disabled for the current profile
        "RestoreLocalFirewallDefaults     hresult();" & _ ;Restores the local firewall configuration to its default state
        "get_DefaultInboundAction         hresult(int;int*);" & _ ;Indicates the default action for inbound traffic
        "put_DefaultInboundAction         hresult(int;int);" & _ ;Specifies the default action for inbound traffic
        "get_DefaultOutboundAction        hresult(int;int*);" & _ ;Indicates the default action for outbound traffic
        "put_DefaultOutboundAction        hresult(int;int);" & _ ;Specifies the default action for outbound traffic
        "get_IsRuleGroupCurrentlyEnabled  hresult(wstr;short*);" & _ ;Determines whether a specified group of firewall rules are enabled or disabled for the current profile
        "get_LocalPolicyModifyState       hresult(int*);" ;Determines if adding or setting a rule or group of rules will take effect in the current firewall profile
; ================================================================================================================================================================================
#EndRegion Global Variables and Constants


#Region Public NetProfile2_Functions
; #CURRENT# ======================================================================================================================================================================
;  _NetFw_EnableRuleGroup
;  _NetFw_Get_BlockAllInboundTraffic
;  _NetFw_Get_CurrentProfileTypes
;  _NetFw_Get_DefaultInboundAction
;  _NetFw_Get_DefaultOutboundAction
;  _NetFw_Get_ExcludedInterfaces
;  _NetFw_Get_FirewallEnabled
;  _NetFw_Get_IsRuleGroupCurrentlyEnabled
;  _NetFw_Get_LocalPolicyModifyState
;  _NetFw_Get_NotificationsDisabled
;  _NetFw_Get_Rules
;  _NetFw_Get_ServiceRestriction
;  _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled
;  _NetFw_Initialize
;  _NetFw_IsRuleGroupEnabled
;  _NetFw_Put_BlockAllInboundTraffic
;  _NetFw_Put_DefaultInboundAction
;  _NetFw_Put_DefaultOutboundAction
;  _NetFw_Put_ExcludedInterfaces
;  _NetFw_Put_FirewallEnabled
;  _NetFw_Put_NotificationsDisabled
;  _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled
;  _NetFw_RestoreLocalFirewallDefaults
; ================================================================================================================================================================================
; #INTERNAL FUNCTIONS#============================================================================================================================================================
;  __CreateVariant
;  __ExtractVariantStrings
;  __GetAdapterNames
;  __GetAdaptersAddresses
;  __IsValidInterface
;  __SafeArrayCreateVector
;  __SafeArrayPutElement
;  __SetVariant
;  __StringArrayToVariantArray
;  __StringToVariant
;  __SysAllocStringLen
;  __SysFreeString
;  __VariantToString
; ================================================================================================================================================================================

; #FUNCTION _NetFw_EnableRuleGroup# ==============================================================================================================================================
; Author.......: Bilgus
; Description..: Enables or disables a specified group of firewall rules
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345), $bEnabled [True, False]
; Returns......: True on success, False on failure
; ================================================================================================================================================================================

Func _NetFw_EnableRuleGroup($iProfileType, $sRuleGroup, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.EnableRuleGroup($iProfileType, $sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_EnableRuleGroup

; #FUNCTION _NetFw_Get_BlockAllInboundTraffic# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether the firewall should not allow inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_BlockAllInboundTraffic($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_BlockAllInboundTraffic($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_BlockAllInboundTraffic

; #FUNCTION _NetFw_Get_CurrentProfileTypes# ======================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the currently active firewall profile(s)
; Parameters...:
; Returns......: $iCurrentProfilesBitMask ($iProfileType) [1|2|4]
; ================================================================================================================================================================================

Func _NetFw_Get_CurrentProfileTypes()
    Local $iResult, $iCurrentProfilesBitMask = 0

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_CurrentProfileTypes($iCurrentProfilesBitMask)
    EndIf

    Return SetError($iResult, Null, $iCurrentProfilesBitMask)
EndFunc   ;==>_NetFw_Get_CurrentProfileTypes

; #FUNCTION _NetFw_Get_DefaultInboundAction# =====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates the default action for inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: $iAction [0, 1, 2], -1 on failure
; ================================================================================================================================================================================

Func _NetFw_Get_DefaultInboundAction($iProfileType)
    Local $iResult, $iAction = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_DefaultInboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, $iAction)
EndFunc   ;==>_NetFw_Get_DefaultInboundAction

; #FUNCTION _NetFw_Get_DefaultOutboundAction# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates the default action for outbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......:
; ================================================================================================================================================================================

Func _NetFw_Get_DefaultOutboundAction($iProfileType)
    Local $iResult, $iAction = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_DefaultOutboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, $iAction)
EndFunc   ;==>_NetFw_Get_DefaultOutboundAction

; #FUNCTION _NetFw_Get_ExcludedInterfaces# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates a list of interfaces on which firewall settings are excluded
; .............: Due to a bug in this function the program architecture must match the OS Arch in order to use this function See below for more information
; .............: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bSupressArchWarning [True, False] Block msgbox error on wrong architecture
; Returns......: $aInterfaces Array of Strings containing friendly name excluded interface, 0 length array on failure or if no excluded interfaces exist
; ================================================================================================================================================================================

Func _NetFw_Get_ExcludedInterfaces($iProfileType, $bSupressArchWarning = False)
    Local Const $MB_ICONERROR = 16
    Local Static $bIsWarned = $bSupressArchWarning
    Local $iResult
    Local $tVariant = __CreateVariant()

    Local $aInterfaces[0]
    If Not @AutoItX64 And @OSArch <> "X86" Then
        If $bIsWarned Then
            ConsoleWriteError("Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces" & @CRLF)
        Else
            MsgBox($MB_ICONERROR, "INetFwPolicy2 Error", "Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces")
        EndIf
        $bIsWarned = True
        Return SetError(1, 0, $aInterfaces)
    EndIf

    While __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize)

        $iResult = $__g_oINetFwPolicy2.get_ExcludedInterfaces($iProfileType, DllStructGetPtr($tVariant))
        If $iResult <> $S_OK Then ExitLoop

        If DllStructGetData($tVariant, "vt") <> BitOR($NET_FW_VT_VARIANT, $NET_FW_VT_ARRAY) Then
            $iResult = $E_NOTIMPL
            ExitLoop
        EndIf

        $aInterfaces = __ExtractVariantStrings(DllStructGetPtr($tVariant))

        ExitLoop
    WEnd

    Return SetError($iResult, Null, $aInterfaces)
EndFunc   ;==>_NetFw_Get_ExcludedInterfaces

; #FUNCTION _NetFw_Get_FirewallEnabled# ==========================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether a firewall is enabled locally
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_FirewallEnabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_FirewallEnabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_FirewallEnabled

; #FUNCTION _NetFw_Get_IsRuleGroupCurrentlyEnabled# ==============================================================================================================================
; Author.......: Bilgus
; Description..: Determines whether a specified group of firewall rules are enabled or disabled for the current profile
; Parameters...: $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345)
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_IsRuleGroupCurrentlyEnabled($sRuleGroup)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_IsRuleGroupCurrentlyEnabled($sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_IsRuleGroupCurrentlyEnabled

; #FUNCTION _NetFw_Get_LocalPolicyModifyState# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Determines if adding or setting a rule or group of rules will take effect in the current firewall profile
; Parameters...:
; Returns......: $iModifyState [0, 1, 2], -1 on failure
; ================================================================================================================================================================================

Func _NetFw_Get_LocalPolicyModifyState()
    Local $iResult, $iModifyState = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_LocalPolicyModifyState($iModifyState)
    EndIf

    Return SetError($iResult, Null, $iModifyState)
EndFunc   ;==>_NetFw_Get_LocalPolicyModifyState

; #FUNCTION _NetFw_Get_NotificationsDisabled# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether interactive firewall notifications are disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_NotificationsDisabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_NotificationsDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_NotificationsDisabled

; #FUNCTION _NetFw_Get_Rules# ====================================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the interface to collection of firewall rules
; Parameters...:
; Returns......: Pointer to INetFwRules Object, Null on failure
; ================================================================================================================================================================================

Func _NetFw_Get_Rules()
    Local $iResult
    Local $tINetFwRules = DllStructCreate("ptr pObject")

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_Rules(DllStructGetPtr($tINetFwRules))
    EndIf

    Return SetError($iResult, Null, DllStructGetData($tINetFwRules, "pObject"))
EndFunc   ;==>_NetFw_Get_Rules

; #FUNCTION _NetFw_Get_ServiceRestriction# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the interface used to access the Windows Service Hardening store
; Parameters...:
; Returns......: Pointer to INetFwServiceRestriction Object, Null on failure
; ================================================================================================================================================================================

Func _NetFw_Get_ServiceRestriction()
    Local $iResult
    Local $tINetFwServiceRestriction = DllStructCreate("ptr pObject")

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_ServiceRestriction(DllStructGetPtr($tINetFwServiceRestriction))
    EndIf

    Return SetError($iResult, Null, DllStructGetData($tINetFwServiceRestriction, "pObject"))
EndFunc   ;==>_NetFw_Get_ServiceRestriction

; #FUNCTION _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled# =============================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled

; #FUNCTION _NetFw_Initialize# ===================================================================================================================================================
; Author.......: Bilgus
; Description..: Initializes NetFwPolicy2 Interface Returns True if Interface is valid False if not
; .............: Called automatically on first use of a _NetFw_ function
; Parameters...: $bInitialize [True, False - Frees interface]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Initialize($bInitialize = True)
    Local $iResult
    If $bInitialize Then
        Local $oObj = ObjCreate("HNetCfg.FwPolicy2")
        Local $sIID = ObjName($oObj, 7) ;Get sIID

        ;Redefine the v-table with our own definitions
        $__g_oINetFwPolicy2 = ObjCreateInterface($oObj, $sIID, $dtag_INetFwPolicy2)
        $iResult = @error
        ;sIID_INetFwPolicy2 = "{98325047-C671-4174-8D81-DEFCD3F03186}"
        ;sCLSID_NetFwPolicy2 = "{E2B3C97F-6AE1-41AC-817A-F6F92166D7DD}"
    Else
        $__g_oINetFwPolicy2 = 0
    EndIf

    If $iResult Or (Not IsObj($__g_oINetFwPolicy2)) Then $bInitialize = False

    Return SetError($iResult, Null, $bInitialize)
EndFunc   ;==>_NetFw_Initialize

; #FUNCTION _NetFw_IsRuleGroupEnabled# ===========================================================================================================================================
; Author.......: Bilgus
; Description..: Determines whether a specified group of firewall rules are enabled or disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345)
; Returns......: True if enabled False if disabled or doesn't exist
; ================================================================================================================================================================================

Func _NetFw_IsRuleGroupEnabled($iProfileType, $sRuleGroup)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.IsRuleGroupEnabled($iProfileType, $sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_IsRuleGroupEnabled

; #FUNCTION _NetFw_Put_BlockAllInboundTraffic# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether the firewall should not allow inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_BlockAllInboundTraffic($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_BlockAllInboundTraffic($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_BlockAllInboundTraffic

; #FUNCTION _NetFw_Put_DefaultInboundAction# =====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies the default action for inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $iAction [0, 1, 2]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_DefaultInboundAction($iProfileType, $iAction)
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_DefaultInboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_DefaultInboundAction

; #FUNCTION _NetFw_Put_DefaultOutboundAction# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies the default action for outbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $iAction [0, 1, 2]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_DefaultOutboundAction($iProfileType, $iAction)
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_DefaultOutboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_DefaultOutboundAction

; #FUNCTION _NetFw_Put_ExcludedInterfaces# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies a list of interfaces on which firewall settings are excluded
; .............: Due to a bug in this function the program architecture must match the OS Arch in order to use this function See below for more information
; .............: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $aInterfaces [String Array containg names of interfaces to exclude], $bSupressArchWarning [True, False] Block msgbox error on wrong architecture
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_ExcludedInterfaces($iProfileType, $aInterfaces, $bSupressArchWarning = False)
    Local Const $MB_ICONERROR = 16
    Local Static $bIsWarned = $bSupressArchWarning

    If Not @AutoItX64 And @OSArch <> "X86" Then
        If $bIsWarned Then
            ConsoleWriteError("Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces" & @CRLF)
        Else
            MsgBox($MB_ICONERROR, "INetFwPolicy2 Error", "Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces")
        EndIf
        $bIsWarned = True
        Return SetError(1, Null, False)
    EndIf

    Local $iResult
    Local $aNeedsFreed[0] ;Returns variant structs containing Bstr's that need freed
    Local $pSafeArray ;Needed to keep valid reference

    Local $aValidInterfaces[UBound($aInterfaces)]

    ;Remove Invalid Interfaces from list.. ALL Interface names must be valid otherwise the function crashes
    Local $sAdapterNames = __GetAdapterNames()

    Local $j = 0
    For $i = 0 To UBound($aInterfaces) - 1
        If StringInStr($sAdapterNames, $aInterfaces[$i] & ";") > 0 Then
            $aValidInterfaces[$j] = $aInterfaces[$i]
            $j += 1
        EndIf
    Next
    ReDim $aValidInterfaces[$j]

    Local $tVariant = __StringArrayToVariantArray($aValidInterfaces, $pSafeArray, $aNeedsFreed)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_ExcludedInterfaces($iProfileType, DllStructGetPtr($tVariant))
    EndIf

    For $i = 0 To UBound($aNeedsFreed) - 1
        ;Free Bstr's
        __SysFreeString(DllStructGetData($aNeedsFreed[$i], "data"))
    Next

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_ExcludedInterfaces

; #FUNCTION _NetFw_Put_FirewallEnabled# ==========================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether a firewall is enabled locally (the effective result may differ due to group policy settings)
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_FirewallEnabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_FirewallEnabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_FirewallEnabled

; #FUNCTION _NetFw_Put_NotificationsDisabled# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether interactive firewall notifications are disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_NotificationsDisabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_NotificationsDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_NotificationsDisabled

; #FUNCTION _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled# =============================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled

; #FUNCTION _NetFw_RestoreLocalFirewallDefaults# =================================================================================================================================
; Author.......: Bilgus
; Description..: Restores the local firewall configuration to its default state
; Parameters...:
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_RestoreLocalFirewallDefaults()
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.RestoreLocalFirewallDefaults()
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_RestoreLocalFirewallDefaults
#EndRegion Public NetProfile2_Functions

#Region Internal_Functions

; #FUNCTION CreateVariant# =======================================================================================================================================================
; Author.......: Bilgus
; Description..: Creates a Variant sized to the OS architecture 64bit Os Variants are 24 bytes where as X86 uses 16 byte Variants
; Parameters...:
; Returns......: $tVariant (DllStruct Sized Appropriately)
; ================================================================================================================================================================================

Func __CreateVariant()
    Local Const $tagVARIANT_PTR = "word vt;word r1;word r2;word r3;ptr data; ptr"
    ; Thanks @AutoItObject-Team, LarsJ?
    ; The Variant structure takes up 16/24 bytes when running 32/64 bit
    ; Space for the data element at the end represents 2 pointers
    ; This is 8 bytes running 32 bit and 16 bytes running 64 bit

    Local $tVariant = DllStructCreate($tagVARIANT_PTR)

    Return $tVariant
EndFunc   ;==>__CreateVariant

; #FUNCTION ExtractVariantStrings# ===============================================================================================================================================
; Author.......: Bilgus
; Description..: Extracts Strings from Passed Variant Array and places them into an Autoit Array
; Parameters...: $pVariant (Pointer to a Variant)
; Returns......: Array containg each string on success Empty array on failure or if no strings were contained
; ================================================================================================================================================================================

Func __ExtractVariantStrings($pVariant, $sSeparator = "; ")
    Local Const $STR_ENTIRESPLIT = 1, $STR_NOCOUNT = 2
    Local $aEmpty[0]

    If Not $pVariant Then Return SetError(1, 0, $aEmpty)

    Local $sStrings = __VariantToString($pVariant)

    Return SetError(@error, Null, StringSplit($sStrings, $sSeparator, BitOR($STR_ENTIRESPLIT, $STR_NOCOUNT)))
EndFunc   ;==>__ExtractVariantStrings

; #FUNCTION GetAdapterNames# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Uses GetAdaptersAddresses to retrieve a string of adapter FriendlyNames on the computer each name is separated by $sSeparator
; Parameters...: $sSeparator = ";"
; Returns......: String containg adaptor FriendlyNames on success Empty String on failure
; ================================================================================================================================================================================

Func __GetAdapterNames($sSeparator = ";")
    Local Enum Step *2 $GAA_FLAG_SKIP_UNICAST = 0x1, $GAA_FLAG_SKIP_ANYCAST, $GAA_FLAG_SKIP_MULTICAST, $GAA_FLAG_SKIP_DNS_SERVER
    Local $iFlags = BitOR($GAA_FLAG_SKIP_UNICAST, $GAA_FLAG_SKIP_ANYCAST, $GAA_FLAG_SKIP_MULTICAST, $GAA_FLAG_SKIP_DNS_SERVER)

    Local Const $tagIP_ADAPTER_FRIENDLYNAME = "ulong;dword;ptr Next;ptr;ptr;ptr;ptr;ptr;ptr;ptr; ptr FriendlyName;"
    Local $tIP_ADAPTER_FRIENDLYNAME, $sAdapterNames = ""

    Local $tBuf_AdapterAddresses = __GetAdaptersAddresses(0, $iFlags)
    Local $iError = @error

    While Not $iError
        Local $pBuf_AdapterAddress = DllStructGetPtr($tBuf_AdapterAddresses)

        While $pBuf_AdapterAddress
            $tIP_ADAPTER_FRIENDLYNAME = DllStructCreate($tagIP_ADAPTER_FRIENDLYNAME, $pBuf_AdapterAddress)
            $sAdapterNames &= _WinAPI_GetString(DllStructGetData($tIP_ADAPTER_FRIENDLYNAME, "FriendlyName")) & $sSeparator
            $iError = @error
            If $iError Then ExitLoop
            $pBuf_AdapterAddress = DllStructGetData($tIP_ADAPTER_FRIENDLYNAME, "Next")
        WEnd
        ExitLoop
    WEnd

    Return SetError($iError, Null, $sAdapterNames)
EndFunc   ;==>__GetAdapterNames

; #FUNCTION GetAdaptersAddresses# ================================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the addresses associated with the adapters on the local computer
; Parameters...: $iFamily = 0 [0,2,23], $iFlags = 0 [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400]
; Returns......: $tBuf_AdapterAddresses[DllStruct Buffer for further processing of data], Empty variable on Failure
; ================================================================================================================================================================================

Func __GetAdaptersAddresses($iFamily = 0, $iFlags = 0)
    Local Const $ERROR_BUFFER_OVERFLOW = 0x6F
    Local $iError = $ERROR_BUFFER_OVERFLOW
    Local $iSzBuffer = 16000 ;Initial Buffer
    Local $iRetries = 3
    Local $aRet, $tBuf_AdapterAddresses
    Local $hIphlpapi = DllOpen("Iphlpapi.dll")
    While $iRetries > 0
        If Not $hIphlpapi Then
            $iError = $NET_FW_UNKNOWNERROR
            ExitLoop
        EndIf

        While $iError = $ERROR_BUFFER_OVERFLOW And $iRetries > 0
            $iRetries -= 1
            $tBuf_AdapterAddresses = DllStructCreate("byte[" & $iSzBuffer & "]")

            $aRet = DllCall($hIphlpapi, "ulong", "GetAdaptersAddresses", _
                    "ulong", $iFamily, _
                    "ulong", $iFlags, _
                    "ptr", Null, _
                    "ptr", DllStructGetPtr($tBuf_AdapterAddresses), _
                    "dword*", $iSzBuffer)

            If Not @error And IsArray($aRet) Then
                $iError = $aRet[0]
                If $aRet[0] = $ERROR_BUFFER_OVERFLOW Then
                    If $iSzBuffer <= DllStructGetSize($tBuf_AdapterAddresses) Then ExitLoop
                    ContinueLoop
                EndIf
            Else
                $iError = @error
            EndIf

            ExitLoop
        WEnd
        ExitLoop
    WEnd

    DllClose($hIphlpapi)
    Return SetError($iError, Null, $tBuf_AdapterAddresses)
EndFunc   ;==>__GetAdaptersAddresses

; #FUNCTION IsValidInterface# ====================================================================================================================================================
; Author.......: Bilgus
; Description..: Checks if passed Object Variable is an Object
; Parameters...: $oInterface[Object], ByRef $iResult, $fInit[function that attempts to (re) initialize object
; Returns......: True if $oInterface is an object, False on failure and iResult is set to $E_NOINTERFACE
; ================================================================================================================================================================================

Func __IsValidInterface(ByRef $oInterface, ByRef $iResult, $fInit = 0)
    If Not IsObj($oInterface) And $fInit <> 0 Then Call($fInit)
    If @error = 0xDEAD Then ConsoleWriteError("Invalid Init Function" & @CRLF)

    If Not IsObj($oInterface) Then
        ConsoleWriteError("Failed To Retrieve Interface" & @CRLF)
        $iResult = $E_NOINTERFACE
        Return SetError($iResult, Null, False)
    EndIf

    Return True
EndFunc   ;==>__IsValidInterface

; #FUNCTION SafeArrayCreateVector# ===============================================================================================================================================
; Author.......: Bilgus
; Description..: Creates a fixed size one-dimensional array
; Parameters...: $iVType[ushort VARTYPE (VT_EMPTY and VT_NULL are not allowed)], $iElements[Integer Number of elements to create], $iLBound = 0[Integer Lower bound of array]
; Returns......: Pointer to SafeArray on success Null on failure
; ================================================================================================================================================================================

Func __SafeArrayCreateVector($iVType, $iElements, $iLBound = 0, $vDll = "OleAut32.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "ptr", "SafeArrayCreateVector", "ushort", $iVType, "long", $iLBound, "ulong", $iElements)

    If Not @error And IsArray($aRet) Then
        If $aRet[0] <> Null Then
            Return $aRet[0]
        EndIf
        $iError = $NET_FW_UNKNOWNERROR
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, Null)
EndFunc   ;==>__SafeArrayCreateVector

; #FUNCTION SafeArrayPutElement# =================================================================================================================================================
; Author.......: Bilgus
; Description..: Stores $pdata at the specified element location in the array
; Parameters...: $pSafeArray[Pointer to SafeArray], $iIndex[Integer element to place data], $pData[Pointer to data to be inserted]
; Returns......: True on success False on error
; ================================================================================================================================================================================

Func __SafeArrayPutElement($pSafeArray, $iIndex, $pData, $vDll = "OleAut32.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "long", "SafeArrayPutElement", "ptr", $pSafeArray, "long*", $iIndex, "ptr", $pData)

    If Not @error And IsArray($aRet) Then
        $iError = $aRet[0]
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, ($iError = $S_OK))
EndFunc   ;==>__SafeArrayPutElement

; #FUNCTION SetVariant# ==========================================================================================================================================================
; Author.......: Bilgus
; Description..: Stores $iVarType and $pData at the specified element location in the variant
; Parameters...: $tVariant[DllStruct Variant], $VarType[The VT_* Constant], $pData[Pointer to data to be inserted]
; Returns......: True on success False on error
; ================================================================================================================================================================================

Func __SetVariant(ByRef $tVariant, $iVarType, $pData)

    Local $iError
    If IsDllStruct($tVariant) Then
        If Not DllStructSetData($tVariant, "vt", $iVarType) Then $iError = BitOR($iError, 1)
        If Not DllStructSetData($tVariant, "data", $pData) Then $iError = BitOR($iError, 2)
    Else
        $iError = 3
    EndIf

    Return SetError($iError, Null, ($iError = 0))
EndFunc   ;==>__SetVariant

; #FUNCTION StringArrayToVariantArray# ===========================================================================================================================================
; Author.......: Bilgus
; Description..: Copies an array of AutoIt strings into a variant array each string is Converted to a BSTR and Placed in a separate Variant
; .............: Top Level Variant is of type (VT_VARIANT|VT_ARRAY) each sub Variant is type (VT_BSTR) and contains an individual BSTR
;..............: $aNeedsFreed holds the sub level variants, The BSTRs within each needs freed when you are finished using them
;..............: $pSafeArray should be passed in as an empty variable to hold a reference to the SafeArray data
;..............: $aNeedsFreed should be an empty array in the form of $aNeedsFreed[0] the function will redim it as necessary
;..............: $tVariant will be a completely empty variant if there are no strings passed within $aArrStrings
; Parameters...: $aArrStrings, ByRef $pSafeArray[EMPTY VARIABLE], ByRef $aNeedsFreed[0]{0 dim array}
; Returns......: $tVariant (DllStruct Containg the Passed Strings)
; ================================================================================================================================================================================

Func __StringArrayToVariantArray($aArrStrings, ByRef $pSafeArray, ByRef $aNeedsFreed)
    ;NOTE!, You Need To Free pBstr's When you are finished with them
    ;$aNeedsFreed Returns variants containg the Bstr's
    Local $iError
    Local $tVariant = __CreateVariant()
    Local $iCtStrings = UBound($aArrStrings)
    ReDim $aNeedsFreed[$iCtStrings]
    While $iCtStrings > 0 ;If The array is empty we want to return empty variant
        $pSafeArray = __SafeArrayCreateVector($NET_FW_VT_VARIANT, $iCtStrings)
        $iError = @error
        If $iError Then ExitLoop

        For $i = 0 To $iCtStrings - 1
            $aNeedsFreed[$i] = __CreateVariant();Create a sub Variant to hold the BSTR

            __StringToVariant($aArrStrings[$i], $aNeedsFreed[$i])
            $iError = @error
            If $iError Then ExitLoop

            __SafeArrayPutElement($pSafeArray, $i, DllStructGetPtr($aNeedsFreed[$i]))
            $iError = @error
            If $iError Then ExitLoop
        Next

        If Not $iError Then
            __SetVariant($tVariant, BitOR($NET_FW_VT_VARIANT, $NET_FW_VT_ARRAY), $pSafeArray)
            $iError = @error
        EndIf

        ExitLoop
    WEnd
    Return SetError($iError, Null, $tVariant)
EndFunc   ;==>__StringArrayToVariantArray

; #FUNCTION StringToVariant# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Copies an AutoIt string into an allocated BSTR Which is placed into a Variant with type VT_BSTR
; Parameters...: $sString, ByRef $tVariant (Variant DllStruct)
; Returns......: True on Success False on Failure
; ================================================================================================================================================================================

Func __StringToVariant($sString, ByRef $tVariant)
    ;NOTE!, YOU Need To Free pBstr When you are finished with it ;__SysFreeString($pBstr)
    Local $pBstr = __SysAllocStringLen($sString)
    Local $iError = @error

    If Not $iError And $pBstr Then
        __SetVariant($tVariant, $NET_FW_VT_BSTR, $pBstr)
        $iError = @error
    Else
        __SetVariant($tVariant, 0, 0)
        $iError = BitOR(@error, $iError)
    EndIf

    Return SetError($iError, Null, ($iError = 0))
EndFunc   ;==>__StringToVariant

; #FUNCTION SysAllocStringLen# ======================================================================================================================================================
; Author.......: Bilgus
; Description..: Allocates a new BSTR and copies the passed AutoIt string into it.
; Parameters...: $sString
; Returns......: NULL on error otherwise pointer to system allocated BSTR
; ================================================================================================================================================================================

Func __SysAllocStringLen($sString, $vDll = "OleAut32.dll")
    ;NOTE!, YOU Need To Free pBstr When you are finished with it ;__SysFreeString($pBstr)
    Local $iError

    Local $aRet = DllCall($vDll, "ptr", "SysAllocStringLen", "wstr", $sString, "uint", StringLen($sString))

    If Not @error And IsArray($aRet) Then
        If $aRet[0] <> Null Then
            Return $aRet[0]
        Else
            $iError = $NET_FW_UNKNOWNERROR
        EndIf
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, Null)
EndFunc   ;==>__SysAllocStringLen

; #FUNCTION SysFreeString# =======================================================================================================================================================
; Author.......: Bilgus
; Description..: Frees a SysAllocString
; Parameters...: $pBstr (Pointer to a BSTR)
; Returns......: None
; ================================================================================================================================================================================

Func __SysFreeString($pBstr, $vDll = "OleAut32.dll")
    DllCall($vDll, "NONE", "SysFreeString", "ptr", $pBstr)
    Return SetError(@error, Null, (@error = 0))
EndFunc   ;==>__SysFreeString

; #FUNCTION VariantToString# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Converts VT_BSTR to an AutoIt string
; Parameters...: $pVariant (Pointer to a Variant)
; Returns......: String Contained in passed Variant
; ================================================================================================================================================================================

Func __VariantToString($pVariant, $vDll = "Propsys.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "long", "VariantToString", "ptr", $pVariant, "wstr", "", "uint", 65535)

    If Not @error And IsArray($aRet) Then
        If $aRet[0] = $S_OK Then
            Return $aRet[2]
        Else
            $iError = $aRet[0]
        EndIf
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, "")
EndFunc   ;==>__VariantToString
#EndRegion Internal_Functions

 

Test Script:

Spoiler
;Test Script For INetFWPolicy2
#RequireAdmin

#include <INetFwPolicy2COM.au3>
#include <GUIConstantsEx.au3>

Global $sOutputAccumulated

;_NetFw_Initialize(True) ;Initialize interface done automatic on first use of a function

Test_Get_CurrentProfileTypes()
Test_Get_LocalPolicyModifyState()
Test_FirewallEnabled()
Test_ExcludedInterfaces()
Test_Rules()
Test_ServiceRestriction()
Test_RuleGroupEnabled()
Test_DefaultAction()

_NetFw_Initialize(False) ;Un-Initialize (Frees) Interface

$sOutputAccumulated &= "Done!" & @CRLF

Global $hGUI = GUICreate("INetFWPolicy2", 600, 400)
Global $idEdit = GUICtrlCreateEdit($sOutputAccumulated, 5, 5, 590, 390)

; Display the GUI.
GUISetState(@SW_SHOW, $hGUI)

; Loop until the user exits.
While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE, $idOK
            ExitLoop

    EndSwitch
WEnd

; Delete the GUI and all controls.
GUIDelete($hGUI)
Exit

Func Test_DefaultAction()
    WriteOutput("Default Inbound/Outbound Actions:" & @CRLF)
    Local $DefaultOutbound = _NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)
    Local $DefaultInbound = _NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)
    WriteOutput("Private Outbound: " & DefaultActionToString($DefaultOutbound) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString($DefaultInbound) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_BLOCK)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_BLOCK)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_ALLOW)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_ALLOW)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_MAX)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_MAX)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $DefaultOutbound)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $DefaultInbound)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF & @CRLF)
EndFunc   ;==>Test_DefaultAction

Func Test_ExcludedInterfaces()
    WriteOutput("get Excluded Interfaces:" & @CRLF)

    WriteOutput("Domain: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_DOMAIN)) & @CRLF)

    Local $aPrivateExcluded = _NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE) ; For restoration..
    WriteOutput("Private: " & @CRLF & PrintArray($aPrivateExcluded) & @CRLF)

    WriteOutput("Public: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PUBLIC)) & @CRLF)

    WriteOutput(@CRLF)
    WriteOutput("Put Excluded Interfaces:" & @CRLF)

    Local $aInterfaces[4] = ["Wireless Network Connection", "Wireless Network Connection 2", "Local Area Connection", "Local Area Connection 2"]
    _NetFw_Put_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE, $aInterfaces)

    WriteOutput("Private: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE, $aPrivateExcluded)

    WriteOutput("Private: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

EndFunc   ;==>Test_ExcludedInterfaces

Func Test_FirewallEnabled()
    WriteOutput("Firewall Enabled:" & @CRLF)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_DOMAIN)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_PUBLIC)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_PRIVATE)
EndFunc   ;==>Test_FirewallEnabled

Func Test_Get_CurrentProfileTypes()
    Local $iCurrentProfilesBitMask = _NetFw_Get_CurrentProfileTypes()
    Local $sProfiles = "CurrentProfiles: " & ProfileTypeToString($iCurrentProfilesBitMask)
    WriteOutput($sProfiles & @CRLF & @CRLF)
EndFunc   ;==>Test_Get_CurrentProfileTypes

Func Test_Get_LocalPolicyModifyState()
    Local $iModifyState = _NetFw_Get_LocalPolicyModifyState()
    WriteOutput("Policy Modify State: " & ModifyStateToString($iModifyState) & @CRLF & @CRLF)
EndFunc   ;==>Test_Get_LocalPolicyModifyState

Func Test_RuleGroupEnabled()
    WriteOutput("Rule Group Enabled:" & @CRLF)
    Local $bEnabled = _NetFw_Get_IsRuleGroupCurrentlyEnabled("Remote Assistance")
    WriteOutput("Remote Assistance Current Profile: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF)
    _NetFw_EnableRuleGroup($NET_FW_PROFILE2_PRIVATE, "Remote Assistance", Not $bEnabled)

    $bEnabled = _NetFw_Get_IsRuleGroupCurrentlyEnabled("Remote Assistance")
    WriteOutput("Remote Assistance Current Profile: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF)
    _NetFw_EnableRuleGroup($NET_FW_PROFILE2_PRIVATE, "Remote Assistance", Not $bEnabled)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

EndFunc   ;==>Test_RuleGroupEnabled

Func Test_Rules()
    WriteOutput("Pointer INetFwRule = " & Hex(_NetFw_Get_Rules()) & @CRLF & @CRLF)
EndFunc   ;==>Test_Rules

Func Test_ServiceRestriction()
    WriteOutput("Pointer INetFwServiceRestriction = " & Hex(_NetFw_Get_ServiceRestriction()) & @CRLF & @CRLF)
EndFunc   ;==>Test_ServiceRestriction

Func DefaultActionToString($iAction)
    Local $sAction
    Switch $iAction
        Case $NET_FW_ACTION_BLOCK
            $sAction = "Block"
        Case $NET_FW_ACTION_ALLOW
            $sAction = "Allow"
        Case $NET_FW_ACTION_MAX
            $sAction = "Max"
        Case Else
            $sAction = "Error"
    EndSwitch
    Return $sAction
EndFunc   ;==>DefaultActionToString

Func ModifyStateToString($iModifyState)
    Local $sModifyState
    Switch $iModifyState
        Case $NET_FW_MODIFY_STATE_OK
            $sModifyState = "OK"
        Case $NET_FW_MODIFY_STATE_GP_OVERRIDE
            $sModifyState = "Group Policy Override"
        Case $NET_FW_MODIFY_STATE_INBOUND_BLOCKED
            $sModifyState = "Inbound Blocked"
        Case Else
            $sModifyState = "Error"
    EndSwitch
    Return $sModifyState
EndFunc   ;==>ModifyStateToString

Func PrintArray($aArr)
    $sRet = ""
    If IsArray($aArr) Then
        For $i = 0 To UBound($aArr) - 1
            $sRet &= $aArr[$i] & @CRLF
        Next
    EndIf
    Return $sRet
EndFunc   ;==>PrintArray

Func ProfileTypeToString($iProfileType)
    Local $sProfiles
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_DOMAIN) ? "Domain" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_PRIVATE) ? "Private" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_PUBLIC) ? "Public" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_ALL) = $NET_FW_PROFILE2_ALL ? "All " : "")
    If $sProfiles = "" Then $sProfiles = "FAILED "
    Return $sProfiles
EndFunc   ;==>ProfileTypeToString

Func Toggle_FirewallEnabled($iProfileType)
    Local Const $sFw = "Firewall Profile "
    Local $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF)

    _NetFw_Put_FirewallEnabled($iProfileType, Not $bEnabled)

    $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_FirewallEnabled($iProfileType, Not $bEnabled)

    $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF & @CRLF)
EndFunc   ;==>Toggle_FirewallEnabled

Func WriteOutput($sOutput)

    $sOutputAccumulated &= $sOutput
    ConsoleWrite($sOutput)

EndFunc   ;==>WriteOutput

 

 

Edited by Bilgus
UDF wasn't posted

Share this post


Link to post
Share on other sites

Note: In order to use get/put_ExcludedInterfaces your script must be the same architecture as the underlying OS

so if you are running x64 Windows your script should be x64 as well otherwise it returns random junk

Apparently this is a known bug but MS isn't going to fix it So this udf pops a warning and skips the function

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp

Edited by Bilgus

Share this post


Link to post
Share on other sites

Found an Error in __SysFreeString($pBstr)
Should be:

Func __SysFreeString($pBstr)
    DllCall("OleAut32.dll", "NONE", "SysFreeString", "ptr", $pBstr)
    Return SetError(@error, 0, (@error = 0))
EndFunc   ;==>__SysFreeString

Added: _NetFw_Initialize() to allow Initialization or un-initialize interface

Cleaned Up a few things thanks @ptrex

Changed: Initialization func, Switched to wstr directly instead of ptr to wchar in GroupEnabled funcs and SysAllocStringLen

Edited by Bilgus

Share this post


Link to post
Share on other sites

This UDF should be adde here:
https://www.autoitscript.com/wiki/User_Defined_Functions#Windows

remark: temporary I can't login to WiKi 

 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2019-10-01

Share this post


Link to post
Share on other sites

Will do :) 

Edit: Done

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2019-08-19 - Version 1.4.13.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2019-07-24 - Version 1.3.6.0) - Download - General Help & Support - Example Scripts - Wiki
Outlook Tools (NEW 2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Taks Scheduler (NEW 2019-10-09 - Version 0.9.0.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Bilgus
      Trying to figure out how to do CallByName on AutoIt COM objects due to the lack of being able to set properties within an Execute() statement
      Several Ideas were Tried https://www.autoitscript.com/forum/topic/200129-set-object-properties-with-propertyname-and-value-taken-from-an-array/
      I think this is the best; Patching the vtable of IDispatch so we can intercept a Fake function call ($obj.Au3_CallByName)
      use it like this
      Local $oDictionary = ObjCreate("Scripting.Dictionary") ; EXAMPLE Au3_CallByname_Init() ; (you can optionally provide a classname here but we patch the main Idispatch interface so really no need) $Au3_CallByName = "Add" ; Method we want to call $oDictionary.Au3_CallByName("Test", "Value") Au3_CallByname_Init(False) ; (Not Strictly Needed unhooked on exit) NOTE:  Au3_CallByname_Init() doesn't have to be called at the top of the script, just call it before you need to call by name...
      Code + Example
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_UseX64=y #AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ;Au3CallByName, Bilgus Global $Au3_CallByName = 0 Local $hKernel32 = DllOpen("Kernel32.dll") OnAutoItExitRegister(__CallByNameCleanup) Func __CallByNameCleanup() Au3_CallByName_Init(False) ;Unload DllClose($hKernel32) EndFunc ;==>__CallByNameCleanup ; Takes a pointer to the v-table in a class and replaces specified member Id in it to a new one. Func __HookVTableEntry($pVtable, $iVtableOffset, $pHook, ByRef $pOldRet) ;;https://www.autoitscript.com/forum/topic/107678-hooking-into-the-idispatch-interface/ Local Const $PAGE_READWRITE = 0x04 Local $tpVtable = DllStructCreate("ptr", $pVtable) Local $szPtr = DllStructGetSize($tpVtable) Local $pFirstEntry, $pEntry, $tEntry, $aCall, $flOldProtect, $bStatus ; Dereference the vtable pointer $pFirstEntry = DllStructGetData($tpVtable, 1) $pEntry = $pFirstEntry + ($iVtableOffset * $szPtr) ; Make the memory free for all. Yay! $aCall = DllCall($hKernel32, "int", "VirtualProtect", "ptr", $pEntry, "long", $szPtr, "dword", $PAGE_READWRITE, "dword*", 0) If @error Or Not $aCall[0] Then ConsoleWriteError("Error: Failed To hook vTable" & @CRLF) Return False EndIf $flOldProtect = $aCall[4] $tEntry = DllStructCreate("ptr", $pEntry) $pOldRet = DllStructGetData($tEntry, 1) If $pOldRet <> $pHook Then DllStructSetData($tEntry, 1, $pHook) $bStatus = True Else ;Already Hooked ConsoleWriteError("Error: vTable is already hooked" & @CRLF) $bStatus = False EndIf ;put the memory protect back how we found it DllCall($hKernel32, "int", "VirtualProtect", "ptr", $pEntry, "long", $szPtr, "dword", $flOldProtect, "dword*", 0) Return $bStatus EndFunc ;==>__HookVTableEntry ; Everytime autoit wants to call a method, get or set a property in a object it needs to go to ; IDispatch::GetIDsFromNames. This is our version of that function, note that by defining this ourselves ; we can fool autoit to believe that the object supports a lot of different properties/methods. Func __IDispatch_GetIDsFromNames($pSelf, $riid, $rgszNames, $cNames, $lcid, $rgDispId) Local Const $CSTR_EQUAL = 0x02 Local Const $LOCALE_SYSTEM_DEFAULT = 0x800 Local Const $DISP_E_UNKNOWNNAME = 0x80020006 Local Static $pGIFN = __Pointer_GetIDsFromNames() Local Static $tpMember = DllStructCreate("ptr") If $Au3_CallByName Then Local $hRes, $aCall, $tMember ;autoit only asks for one member $aCall = DllCall($hKernel32, 'int', 'CompareStringW', 'dword', $LOCALE_SYSTEM_DEFAULT, 'dword', 0, 'wstr', "Au3_CallByName", 'int', -1, _ 'struct*', DllStructGetData(DllStructCreate("ptr[" & $cNames & "]", $rgszNames), 1, 1), 'int', -1) If Not @error And $aCall[0] = $CSTR_EQUAL Then ;ConsoleWrite("CallByName: " & $Au3_CallByName & @CRLF) $tMember = DllStructCreate("wchar[" & StringLen($Au3_CallByName) + 1 & "]") DllStructSetData($tMember, 1, $Au3_CallByName) DllStructSetData($tpMember, 1, DllStructGetPtr($tMember)) $rgszNames = $tpMember $Au3_CallByName = 0 EndIf EndIf ;Call the original GetIDsFromNames $hRes = DllCallAddress("LRESULT", $pGIFN, "ptr", $pSelf, "ptr", $riid, _ "struct*", $rgszNames, "dword", $cNames, "dword", $lcid, "ptr", $rgDispId) If @error Then ConsoleWrite("Error: GetIDsFromNames: " & @error & @CRLF) Return $DISP_E_UNKNOWNNAME EndIf Return $hRes[0] EndFunc ;==>__IDispatch_GetIDsFromNames Func __Pointer_GetIDsFromNames($ptr = 0) Local Static $pOldGIFN = $ptr If $ptr <> 0 Then $pOldGIFN = $ptr Return $pOldGIFN EndFunc ;==>__Pointer_GetIDsFromNames Func Au3_CallByName_Init($bHook = True, $classname = "shell.application") Local Const $iOffset_GetIDsFromNames = 5 Local Static $IDispatch_GetIDsFromNames_Callback = 0 Local $oObject, $pObject, $pHook, $pOldGIFN If $bHook Then If $IDispatch_GetIDsFromNames_Callback = 0 Then $IDispatch_GetIDsFromNames_Callback = DllCallbackRegister("__IDispatch_GetIDsFromNames", "LRESULT", "ptr;ptr;ptr;dword;dword;ptr") EndIf $pHook = DllCallbackGetPtr($IDispatch_GetIDsFromNames_Callback) Else $pHook = __Pointer_GetIDsFromNames() If $pHook <= 0 Then Return ;Already Unloaded EndIf $oObject = ObjCreate($classname) $pObject = DllStructSetData(DllStructCreate("ptr"), 1, $oObject) If __HookVTableEntry($pObject, $iOffset_GetIDsFromNames, $pHook, $pOldGIFN) Then __Pointer_GetIDsFromNames($pOldGIFN) ;Save the original pointer to GetIDsFromNames If Not $bHook Then DllCallbackFree($IDispatch_GetIDsFromNames_Callback) $IDispatch_GetIDsFromNames_Callback = 0 EndIf Else ;Error EndIf $oObject = 0 EndFunc ;==>Au3_CallByName_Init ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;TESTS; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Au3_CallByName_Init() #include <ie.au3> Global $oRegistrationInfo = _IECreate() Global $aRegistrationInfo[] = ['Left=10', 'Top= 10', 'Width=450', 'Height=600'] Global $oObject = $oRegistrationInfo Local $oDictionary = ObjCreate("Scripting.Dictionary") Local $oDictionary2 = ObjCreate("Scripting.Dictionary") ;Au3_CallByName_Init($oObject) __TS_TaskPropertiesSet($oObject, $aRegistrationInfo) MsgBox(0, "Info", "Press OK to exit") $oRegistrationInfo.quit $oRegistrationInfo = 0 $oObject = 0 Sleep(1000) For $i = 1 To 10 $Au3_CallByName = "Add" $oDictionary.Au3_CallByName("test1:" & $i, "Dictionary Item: " & $i) Next $Au3_CallByName = "keys" For $sKey In $oDictionary.Au3_CallByName() For $j = 0 To 1 $Au3_CallByName = ($j = 0) ? "Item" : "Exists" ConsoleWrite($sKey & " -> " & $oDictionary.Au3_CallByName($sKey) & @CRLF) Next Next Au3_CallByName_Init(False) ;Unload Au3_CallByName_Init() Local $aRegistrationInfo[] = ['Left=1000', 'Width=450'] ConsoleWrite(@CRLF & "NEW IE" & @CRLF & @CRLF) $oRegistrationInfo = _IECreate() __TS_TaskPropertiesSet($oRegistrationInfo, $aRegistrationInfo) MsgBox(0, "Info", "Press OK to exit") $oRegistrationInfo.quit For $i = 1 To 10 $Au3_CallByName = "Add" $oDictionary2.Au3_CallByName("test2:" & $i, "Dictionary Item: " & $i) Next $Au3_CallByName = "keys" For $sKey In $oDictionary2.Au3_CallByName() For $j = 0 To 1 $Au3_CallByName = ($j = 0) ? "Item" : "Exists" ConsoleWrite($sKey & " -> " & $oDictionary2.Au3_CallByName($sKey) & @CRLF) Next Next Au3_CallByName_Init(False) ;Unload (Not Strictly Needed, Done on Script Close) Func __TS_TaskPropertiesSet(ByRef $oObject, $aProperties) Local $aTemp If IsArray($aProperties) Then For $i = 0 To UBound($aProperties) - 1 $aTemp = StringSplit($aProperties[$i], "=", 2) ; 2 -> $STR_NOCOUNT) If @error Then ContinueLoop ConsoleWrite("Command: $oObject." & $aTemp[0] & " = " & $aTemp[1] & @CRLF) $Au3_CallByName = $aTemp[0] $oObject.Au3_CallByName = $aTemp[1] ConsoleWrite("Result : " & Hex(@error) & @CRLF) ; If @error Then Return SetError(1, @error, 0) Next EndIf EndFunc ;==>__TS_TaskPropertiesSet  
    • By mLipok
      Today, in the end as well, worked out using the Acrobat Reader ActiveX COM Object "AcroPDF.PDF.1"
      #include-once #include <Constants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <Misc.au3> #include <MenuConstants.au3> #include <WinAPI.au3> ;~ Thanks to BrewManNH ;~ http://www.autoitscript.com/forum/topic/134878-guiregistermsg-replacement-for-guictrlsetonevent-and-guigetmsg/ ;~ Thanks to mikell ;~ http://www.autoitscript.com/forum/topic/161985-how-to-close-gui-with-guiregistermsg/ ; Install a custom error handler Global $oMyError = ObjEvent("AutoIt.Error", "_ComErrFunc") Global $__hExampleGUI Global $__idOPEN Global $_fExit Global $__hACROBAT_GUI = '' Global $__idACROBAT_GUI_CTRL_AX = '' Global $__oACROBAT_READER = '' #include <GUIConstantsEx.au3> ;~ GUIRegisterMsg($WM_ERASEBKGND, "_WM_EXTRACTOR") ;~ GUIRegisterMsg($WM_PAINT, "_WM_EXTRACTOR") ;~ GUIRegisterMsg($WM_ACTIVATE, "_WM_EXTRACTOR") ;~ GUIRegisterMsg($WM_CAPTURECHANGED, "_WM_EXTRACTOR") ;~ GUIRegisterMsg($WM_DEVICECHANGE, "_WM_EXTRACTOR") GUIRegisterMsg($WM_EXITSIZEMOVE, "_WM_EXTRACTOR") GUIRegisterMsg($WM_COMMAND, "_WM_EXTRACTOR") GUIRegisterMsg($WM_SYSCOMMAND, "_WM_EXTRACTOR") GUIRegisterMsg($WM_HSCROLL, "_WM_EXTRACTOR") _ExampleProgram_Gui() While 1 Sleep(10) If $_fExit Then _ACROBAT_GUI_DELETE() DeleteGui() Exit EndIf WEnd Func DeleteGui() GUIDelete($__hExampleGUI) EndFunc ;==>DeleteGui Func _ExampleProgram_Gui() ; Create a GUI with various controls. $__hExampleGUI = GUICreate("Example") $__idOPEN = GUICtrlCreateButton("&Open", 310, 370, 85, 25) ; Display the GUI. GUISetState(@SW_SHOW, $__hExampleGUI) EndFunc ;==>_ExampleProgram_Gui #Region ACROBAT FUNCTION Func _AcrobatInit() $__oACROBAT_READER = ObjCreate("AcroPDF.PDF.1"); Return $__oACROBAT_READER.GetVersions EndFunc ;==>_AcrobatInit Func _Acrobat_Events(ByRef $aMSG) If $aMSG[1] = $__hACROBAT_GUI Then Switch $aMSG[0] Case $GUI_EVENT_CLOSE _ACROBAT_GUI_DELETE() EndSwitch EndIf EndFunc ;==>_Acrobat_Events Func _ACROBAT_Destroy() $__oACROBAT_READER = "" ;~ MsgBox(1,'test','destroyed') EndFunc ;==>_ACROBAT_Destroy Func _AcrobatShow($sFile, $sTitle = "PDF ", $iLeft = 50, $iTop = 0, $iWidth = 1000, $iHeight = 700) If FileExists($sFile) Then _AcrobatInit() ; Set option $__oACROBAT_READER.src = $sFile $__oACROBAT_READER.SetLayoutMode(4) $__oACROBAT_READER.SetPageMode(1) $__oACROBAT_READER.SetShowToolbar(0) $__oACROBAT_READER.SetView(1) ; Create GUI $__hACROBAT_GUI = GUICreate($sTitle, $iWidth, $iHeight, $iLeft, $iTop, BitOR($GUI_SS_DEFAULT_GUI, $WS_SIZEBOX, $WS_MAXIMIZEBOX)) $__idACROBAT_GUI_CTRL_AX = GUICtrlCreateObj($__oACROBAT_READER, 5, 5, $iWidth - 20, $iHeight - 10) GUICtrlSetStyle($__idACROBAT_GUI_CTRL_AX, $WS_VISIBLE) GUISetState() EndIf EndFunc ;==>_AcrobatShow Func _ACROBAT_Refresh() If IsObj($__oACROBAT_READER) Then Local $hPreviouslyGui = GUISwitch($__hACROBAT_GUI) GUISetState(@SW_LOCK) Local $iGUI_PDFWidth = WinGetPos($__hACROBAT_GUI)[2] - 20 Local $iGUI_PDFHeight = WinGetPos($__hACROBAT_GUI)[3] - 40 Local $sFile = $__oACROBAT_READER.src ; this below line do not works with Acro Reader ; Local $iCurrentPage = $__oACROBAT_READER.GetNumber Local $iCurrentPage = 0 _ACROBAT_Destroy() GUICtrlDelete($__idACROBAT_GUI_CTRL_AX) _AcrobatInit() $__idACROBAT_GUI_CTRL_AX = GUICtrlCreateObj($__oACROBAT_READER, 5, 5, $iGUI_PDFWidth, $iGUI_PDFHeight) $__oACROBAT_READER.src = $sFile ;~ $__oACROBAT_READER.SetCurrentPage($iCurrentPage) GUISetState(@SW_UNLOCK) GUISwitch($hPreviouslyGui) EndIf EndFunc ;==>_ACROBAT_Refresh Func _ACROBAT_GUI_DELETE() _ACROBAT_Destroy() if IsHWnd($__hACROBAT_GUI) then GUIDelete($__hACROBAT_GUI) EndFunc ;==>_ACROBAT_GUI_DELETE #EndRegion ACROBAT FUNCTION #Region MSG and ERROR HANDLER Func _WM_EXTRACTOR($hWnd, $iMsg, $wParam, $lParam) ;~ ConsoleWrite('! $hWnd = ' & $hWnd & ' $iMsg = ' & $iMsg & '('&HEX($iMsg)&')'& ' $wParam = ' & $wParam & ' $lParam = ' & $lParam & @CRLF) If $hWnd = ControlGetHandle($__hACROBAT_GUI, '', $__idACROBAT_GUI_CTRL_AX) Then ConsoleWrite('! -------------- $hWnd = ' & $hWnd & ' $iMsg = ' & $iMsg & '(' & Hex($iMsg) & ')' & ' $wParam = ' & $wParam & ' $lParam = ' & $lParam & @CRLF) EndIf If $hWnd = $__hACROBAT_GUI Then Switch $iMsg Case $WM_COMMAND #cs Case $WM_ACTIVATE Local $test = BitAND($wParam, 0x00000004) if $test <> 0 then MsgBox(1,'$WM_ACTIVATE','test') _ACROBAT_Refresh() EndIf Case $WM_ERASEBKGND WinGetHandle("[ACTIVE]") if $__hACROBAT_GUI <> _WinAPI_GetWindow ( $__hACROBAT_GUI, $GW_HWNDPREV ) then ConsoleWrite('! Case $WM_ERASEBKGND' & @CRLF) _ACROBAT_Refresh() _WinAPI_RedrawWindow($__hACROBAT_GUI,0,0,$RDW_NOERASE) EndIf Case $WM_PAINT _WinAPI_RedrawWindow($__hACROBAT_GUI,0,0,$RDW_NOERASE) Case $WM_CAPTURECHANGED _ACROBAT_Refresh() Case $WM_DEVICECHANGE _ACROBAT_Refresh() #ce Case $WM_EXITSIZEMOVE _ACROBAT_Refresh() Case $WM_SYSCOMMAND ;~ Local $test = BitAND($wParam, 0xFFF0) Local $test = BitAND($wParam, 0x0000FFFF) Switch $test Case $SC_CLOSE _ACROBAT_GUI_DELETE() Case $SC_CONTEXTHELP Case $SC_DEFAULT Case $SC_HOTKEY Case $SC_HSCROLL Case $SC_KEYMENU Case $SC_MAXIMIZE _ACROBAT_Refresh() Case $SC_MINIMIZE Case $SC_MONITORPOWER Case $SC_MOUSEMENU Case $SC_MOVE ;~ _ACROBAT_Refresh() Case $SC_NEXTWINDOW ;~ _ACROBAT_Refresh() Case $SC_PREVWINDOW ;~ _ACROBAT_Refresh() Case $SC_RESTORE _ACROBAT_Refresh() Case $SC_SCREENSAVE Case $SC_SIZE Case $SC_TASKLIST Case $SC_VSCROLL EndSwitch EndSwitch EndIf If $hWnd = $__hExampleGUI Then Switch $iMsg Case $WM_COMMAND Local $nID = BitAND($wParam, 0x0000FFFF) Local $hCtrl = $lParam Switch $nID Case $__idOPEN if not IsObj($__oACROBAT_READER) then _AcrobatShow(FileOpenDialog("Choose PDF", "C:\Temp", "PDF Files(*.pdf)", 3)) ; put your own start folder here) EndIf EndSwitch Case $WM_SYSCOMMAND Local $test = BitAND($wParam, 0xFFF0) Switch $test Case $SC_CLOSE $_fExit = True Case $SC_CONTEXTHELP Case $SC_DEFAULT Case $SC_HOTKEY Case $SC_HSCROLL Case $SC_KEYMENU Case $SC_MAXIMIZE Case $SC_MINIMIZE Case $SC_MONITORPOWER Case $SC_MOUSEMENU Case $SC_MOVE Case $SC_NEXTWINDOW Case $SC_PREVWINDOW Case $SC_RESTORE Case $SC_SCREENSAVE Case $SC_SIZE Case $SC_TASKLIST Case $SC_VSCROLL EndSwitch EndSwitch EndIf Return $GUI_RUNDEFMSG EndFunc ;==>_WM_EXTRACTOR Func _ComErrFunc() Local $HexNumber = Hex($oMyError.number, 8) MsgBox(0, "AutoItCOM Test", _ "We intercepted a COM Error !" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $oMyError.description & @CRLF & _ "err.windescription:" & @TAB & $oMyError.windescription & @CRLF & _ "err.number is: " & @TAB & $HexNumber & @CRLF & _ "err.lastdllerror is: " & @TAB & $oMyError.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $oMyError.scriptline & @CRLF & _ "err.source is: " & @TAB & $oMyError.source & @CRLF & _ "err.helpfile is: " & @TAB & $oMyError.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $oMyError.helpcontext _ ) SetError(1) EndFunc ;==>_ComErrFunc #EndRegion MSG and ERROR HANDLER Any comments are welcome.
      Cheers
      mLipok
    • By jantograaf
      Hi all,
      I'm trying to write a script that connects with a VBA/COM API to get the status of a connected phone. I've been looking up and down this forum for tips or other user's experiences, but I can't seem to find anything (even remotely) similar. It shouldn't be so hard to do, however.
      Software I'm trying to connect to
      I'm trying to integrate CallCenter by using their API, which is documented over here : JustRemotePhone API Reference
      Things I've tried
      I've tried using ObjCreate but I don't get any result, it always returns the same (negative) error.
      #Version 1 tried ObjCreate("JustRemotePhone.RemotePhoneService") #Version 2 tried ObjCreate("JustRemotePhoneCOM.RemotePhoneService") #Version 3 tried ObjCreate("JustRemotePhoneCOM.RemotePhoneService.Application") None of the three versions I tried seem to deliver any result other than a negative error value which basically says that the given class is not valid.
      I am starting to get the hang of AutoIt by now, but unmanaged programming languages and object-oriented stuff is still quite a grey zone for me. If anyone could help me 'talk' to this application, I'd be immensely grateful!
      Thanks in advance and kind regards from Belgium!
       
      Jan
    • By Rhidlor
      So I'm trying to do some as400 automation and hit a wall when trying to get a COM object. The code on line 8 is failing, the as400.ws file opens with PCSWS.exe so I tried using that as the file path too but that didn't work either. Any and all help is greatly appreciated! 
       
      $file = "C:\Users\Rhidlor\Desktop\as400.ws" If Not FileExists($file) Then MsgBox(0, "Error", "Error finding file") Exit EndIf $object = ObjGet($file) If @error Then MsgBox(0, "Error", "Error getting object") Exit EndIf $object.SendKeys("05")  
    • By Bilgus
      I was Playing around With AutoIt this evening and wondered how hard it would be to get typeinfo like the COM Viewers do only using AutoIt
      Turns out it was pretty easy.
      A Few Notes:
      CAarray info is unfinished I didn't have any objects to test it on so I left it Limited.
      The Object must have IDispatch exposed (ITypeInfo is derivative)
      Its Just a proof of concept Run with it but don't carry scissors
      ITypeInfoCOM.au3
      ITypeInfoTest.au3
       
      Output IWebBrowserApp
       
      Output ObjCreate(MediaPlayer.MediaPlayer.1)
       
×
×
  • Create New...