Snippets ( Windows Settings )

From AutoIt Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Please always credit an author in your script if you use their code. It is only polite.


_ChangeWallpaper

Author: TheOnlyOne








_ChangeWallpaper("c:\Documents and Settings\lo\Skrivebord\gaza.bmp",1) ; only a simple cut & paste

Func _ChangeWallpaper($sFile,$iType)

; Changes the wallpaper to $sFilename using $iType as:
; 1 Tiled
; 2 Centered
; 3 Stretched
; any other value (usually 0) unchanged
;
; Returns
; 0 if everything is allright.
; -1 if $sFile does not exist. @error is set to 1
; -2 if £sFile is not a .bmp file. @error is set to 2

  If Not FileExists($sFile) Then
     SetError(1)
     Return -1
  EndIf
  If StringTrimLeft($sFile,StringInStr($sFile,'.',0,-1)) <> 'bmp' Then
     SetError(2)
     Return -2
  EndIf

  Select
  Case $iType = 1
     RegWrite('HKCU\Control Panel\Desktop','TileWallpaper','reg_sz','1')
     RegWrite('HKCU\Control Panel\Desktop','WallpaperStyle','reg_sz','0')
  Case $iType = 2
     RegWrite('HKCU\Control Panel\Desktop','TileWallpaper','reg_sz','0')
     RegWrite('HKCU\Control Panel\Desktop','WallpaperStyle','reg_sz','0')
  Case $iType = 3
     RegWrite('HKCU\Control Panel\Desktop','TileWallpaper','reg_sz','0')
     RegWrite('HKCU\Control Panel\Desktop','WallpaperStyle','reg_sz','2')
  Case Else

  EndSelect

  RegWrite('HKCU\Control Panel\Desktop','Wallpaper','reg_sz',$sFile)
  DllCall("User32.dll","int","SystemParametersInfo","int",20,"int",0,"str",$sFile,"int",0)
  Return 0
EndFunc

ReturnToContents

_CheckProcess

Author: Valuater








; Notify and Name of any new process started

Global $aProcessList_1 = ProcessList()
AdlibRegister("_CheckProcess")

While 1
	Sleep(20)
WEnd

Func _CheckProcess()
	Local $aProcessList_2 = ProcessList()
	If $aProcessList_2[0][0] > $aProcessList_1[0][0] Then
		MsgBox(4096, '', 'New process: ' & $aProcessList_2[$aProcessList_2[0][0]][0])
		$aProcessList_1[0][0] = $aProcessList_2[0][0]
	Else
		$aProcessList_1[0][0] = $aProcessList_2[0][0]
		; If you close processes this resets the list.s
	EndIf
EndFunc   ;==>_CheckProcess

ReturnToContents

_Clipboard_GetHTML

Author: Mat








#include <ClipBoard.au3>

If (Not _ClipBoard_Open(0)) Then
    ConsoleWriteError("_ClipBoard_Open failed" & @LF)
Else
    Local $sData = _Clipboard_GetHTML()
    Switch @error
        Case 1
            ConsoleWriteError("Could not register CF_HTML format" & @LF)
        Case 2
            ConsoleWriteError("Clipboard data not available in HTML format" & @LF)
        Case 3
            ConsoleWriteError("Invalid HTML format header (missing end or start fragment)" & @LF)
        Case 0
            ConsoleWrite($sData & @LF)
    EndSwitch
EndIf

_ClipBoard_Close()

; #FUNCTION# ====================================================================================================================
; Name ..........: _Clipboard_GetHTML
; Description ...: Retrieves the data from the clipboard in HTML format
; Syntax ........: _Clipboard_GetHTML( )
; Parameters ....: None
; Return values .: Success: Returns the data from the clipbard as html.
;                  Failure: Returns an empty string and sets @error:
;                           | 1 - Could not register CF_HTML format
;                           | 2 - Clipboard data not available in HTML format
;                           | 3 - Invalid HTML format header (missing end or start fragment)
; Author ........: Matt Diesel (Mat)
; Modified ......:
; Remarks .......: This assumes that the clipboard is already open. The _Clipboard_Open function should be called first.
; Related .......:
; Link ..........:
; Example .......: Above.
; ===============================================================================================================================
Func _Clipboard_GetHTML()
    Local $CF_HTML, $pHTML, $tHeader, $asHeader, $asLine, $iStartFragment = -1, $iEndFragment = -1

    ; Register the CF_HTML format
    $CF_HTML = _ClipBoard_RegisterFormat("HTML Format")

    If (Not $CF_HTML) Then Return SetError(1, 0, "") ; Could not register CF_HTML format
    If (Not _ClipBoard_IsFormatAvailable($CF_HTML)) Then Return SetError(2, 0, "") ; Clipboard data not available in HTML format

    $pHTML = _ClipBoard_GetDataEx($CF_HTML)

    $tHeader = DllStructCreate("char t[104]", $pHTML)
    $asHeader = StringSplit(DllStructGetData($tHeader, "t"), @CRLF, 1)

    ; Find start and end of fragment from header.
    For $i = 1 To $asHeader[0]
        $asLine = StringSplit($asHeader[$i], ":")

        Switch $asLine[1]
            Case "StartFragment"
                $iStartFragment = Int($asLine[2])
            Case "EndFragment"
                $iEndFragment = Int($asLine[2])
        EndSwitch
    Next

    If (($iEndFragment < 0) Or ($iStartFragment < 0)) Then Return SetError(3, 0, "") ; Invalid HTML format header (missing end or start fragment)

    $tHeader = DllStructCreate("char t[" & $iEndFragment - $iStartFragment + 1 & "]", $pHTML + $iStartFragment)
    Return DllStructGetData($tHeader, "t")
EndFunc   ;==>_Clipboard_GetHTML

ReturnToContents

_CreateSystemRestorePoint

Author: Pakku








#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

$disable = True ;set True to disable system restore after creating a restore point and False to keep system restore enabled

Opt("TrayMenuMode",1)

$create = TrayCreateItem("Create")
TrayCreateItem("")
$exit = TrayCreateItem("Exit")
TraySetState()

$gui = GUICreate("Create System Restore Point",176,21,@DesktopWidth - 176,@DesktopHeight - 80,$WS_POPUP,$WS_EX_TOOLWINDOW + $WS_EX_TOPMOST)
$input = GUICtrlCreateInput("",0,0,150,21)
$send = GUICtrlCreateButton("OK",150,0,26,21)
GUISetState(@SW_HIDE,$gui)

While 1
    $tray_msg = TrayGetMsg()
    $gui_msg = GUIGetMsg()
    Select
        Case $tray_msg = $create
            GUICtrlSetData($input,"RestorePoint " & @HOUR & ":" & @MIN & ":" & @SEC)
            GUISetState(@SW_SHOW,$gui)
        Case $tray_msg = $exit
            Exit
        Case $gui_msg = $send
            If StringLen(GUICtrlRead($input)) > 0 Then
                GUISetState(@SW_HIDE,$gui)
                _CreateSystemRestorePoint(GUICtrlRead($input),$disable)
            Else
                GUISetState(@SW_HIDE,$gui)
            EndIf
    EndSelect
WEnd

Func _CreateSystemRestorePoint($discription,$disable = True)
    #RequireAdmin
    $obj = ObjGet("winmgmts:{impersonationLevel=impersonate}!root/default:SystemRestore")
    $obj.Enable("")
    $obj.CreateRestorePoint($discription, 12, 100)
    If $disable Then
        $obj.Disable("")
    EndIf
EndFunc

ReturnToContents

Change the master volume setting on Windows Vista and 7

Author: BrewManNH







Additional Info

32 bit bass dll available from: Bass dll

64 bit version of the Bass.dll that can be used on 64 bit machines: 64 Bit Bass dll


; change the master volume setting on Windows Vista and 7 using the Bass library and DLL.

#AutoIt3Wrapper_UseX64=n
#include <bass.au3> ; see above for download information
#include <guiconstantsex.au3>

_Bass_Startup()
_BASS_Init(0, -1, 44100, 0, "")
If @error Then Exit
Global $LastPass = 0
$GUI = GUICreate("Volume control demo")
$MasterVolume = GUICtrlCreateSlider(20, 20, 300, 30)
$Check = GUICtrlCreateCheckbox("Master Volume", 10, 120)
GUISetState()
While 1
    $msg = GUIGetMsg()
    If GUICtrlRead($Check) = $GUI_CHECKED Then
        If  GUICtrlRead($MasterVolume) <> $LastPass Then
            $Test = _Bass_SetVolume((GUICtrlRead($MasterVolume)/ 100)) ; sets the MASTER volume control in Vista/7
            $LastPass = GUICtrlRead($MasterVolume)
        EndIf
    Else
        If  GUICtrlRead($MasterVolume) <> $LastPass Then
            SoundSetWaveVolume(GUICtrlRead($MasterVolume)) ; only affects the applications volume control under Vista/7
            $LastPass = GUICtrlRead($MasterVolume)
        EndIf
    EndIf
    Switch $msg
        Case -3
            _BASS_Free()
            Exit
    EndSwitch
WEnd

ReturnToContents

_IsDEPEnabled

Author: guinness








#include <Constants.au3>

Local $fIsDEPEnabled = _IsDEPEnabled()
Local $iDEPValue = @extended
ConsoleWrite('Is DEP enabled?: ' & $fIsDEPEnabled & ', ' & ' the DEP value is: ' & $iDEPValue & '.' & @CRLF)

; What is DEP?: http://windows.microsoft.com/en-US/windows-vista/What-is-Data-Execution-Prevention
; This checks if DEP is enabled on the system and returns the DEP value via the @extended macro.
; Description about the DEP value can be found at: http://msdn.microsoft.com/en-us/library/windows/desktop/bb736298(v=vs.85).aspx
Func _IsDEPEnabled() ; Idea by UEZ from Windows Screenshooter.
    Local $iPID = Run(@ComSpec & ' /c wmic os get DataExecutionPrevention_SupportPolicy', @SystemDir, @SW_HIDE, $STDOUT_CHILD + $STDERR_CHILD), $sOutput = ''
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
    WEnd
    Local $iDEPValue = Number(StringRight(StringStripWS($sOutput, 8), 1))
    Return SetError(0, $iDEPValue, $iDEPValue > 0)
EndFunc   ;==>_IsDEPEnabled

ReturnToContents

_KillWindow

Author: Valuater








; _KillWindow ( That you know is going to show up)

Func _KillWindow($title)
    Local $Script = 'WinWait("' & $title & '", "")' & @CRLF & 'WinKill("' & $title & '", "")'
    Local $file_loc = @ScriptDir & "\Killer.au3"
    FileDelete($file_loc)
    FileWrite($file_loc, $Script)
    If @Compiled = 1 Then
        $file_exe = FileGetShortName(@AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
        Run($file_exe)
    Else
        $file_au3 = FileGetShortName($file_loc)
        Run(@AutoItExe & " " & $file_au3, "", @SW_HIDE)
    EndIf
EndFunc   ;==>_KillWindow

ReturnToContents

_ProcessKill

Author: guinness








Func _ProcessKill($iPID)
    Local $iTimeOut = 5, $iTimer

    $iTimeOut *= 1000
    $iTimer = TimerInit()
    While ProcessExists($iPID)
        If TimerDiff($iTimer) > $iTimeOut Then
            ExitLoop
        EndIf
        RunWait('TASKKILL /F /PID ' & $iPID, @SystemDir & "\", @SW_HIDE)
        Sleep(20)
    WEnd
    Return Number(ProcessExists($iPID) > 0)
EndFunc   ;==>_ProcessKill

ReturnToContents

_SetCurrentPath

Author: guinness








#include <WinAPI.au3>

ConsoleWrite(_WinAPI_PathFindOnPath(@ScriptName) & @LF)
_SetCurrentPath()
ConsoleWrite(_WinAPI_PathFindOnPath(@ScriptName) & @LF)

Func _SetCurrentPath()
    Return EnvSet("PATH", EnvGet("PATH") & ";" & @ScriptDir & "\")
EndFunc   ;==>_SetCurrentPath

ReturnToContents

_SetComputerName

Author: JScript








;Author: JScript - Snippet Version No. = 1.0
;Snippet was Created Using AutoIt Version = 3.3.8.1, Creation Date = 28/05/12.

#RequireAdmin

_SetComputerName("AutoIt")

Send("#{PAUSE}")

; Sets computer name without restart!
Func _SetComputerName($sCmpName)
    Local $sLogonKey = "HKLMSOFTWAREMicrosoftWindows NTCurrentVersionWinlogon"
    Local $sCtrlKey = "HKLMSYSTEMCurrentControlSet"
    Local $aRet

    ; RagsRevenge -> http://www.autoitscript.com/forum/index.php?showtopic=54091&view=findpost&p=821901
    If StringRegExp($sCmpName, '|/|:|*|?|"|<|>|.|,|~|!|@|#|$|%|^|&|(|)|;|{|}|_|=|+|[|]|x60' & "|'", 0) = 1 Then Return 0

    ; 5 = ComputerNamePhysicalDnsHostname
    $aRet = DllCall("Kernel32.dll", "BOOL", "SetComputerNameEx", "int", 5, "str", $sCmpName)
    If $aRet[0] = 0 Then Return SetError(1, 0, 0)
    RegWrite($sCtrlKey & "ControlComputernameActiveComputername", "ComputerName", "REG_SZ", $sCmpName)
    RegWrite($sCtrlKey & "ControlComputernameComputername", "ComputerName", "REG_SZ", $sCmpName)
    RegWrite($sCtrlKey & "ServicesTcpipParameters", "Hostname", "REG_SZ", $sCmpName)
    RegWrite($sCtrlKey & "ServicesTcpipParameters", "NV Hostname", "REG_SZ", $sCmpName)
    RegWrite($sLogonKey, "AltDefaultDomainName", "REG_SZ", $sCmpName)
    RegWrite($sLogonKey, "DefaultDomainName", "REG_SZ", $sCmpName)
    RegWrite("HKEY_USERS.DefaultSoftwareMicrosoftWindows MediaWMSDKGeneral", "Computername", "REG_SZ", $sCmpName)

    ; Set Global Environment Variable
    RegWrite($sCtrlKey & "ControlSession ManagerEnvironment", "Computername", "REG_SZ", $sCmpName)
    ; http://msdn.microsoft.com/en-us/library/ms686206%28VS.85%29.aspx
    $aRet = DllCall("Kernel32.dll", "BOOL", "SetEnvironmentVariable", "str", "Computername", "str", $sCmpName)
    If $aRet[0] = 0 Then Return SetError(2, 0, 0)
    ; http://msdn.microsoft.com/en-us/library/ms644952%28VS.85%29.aspx
    $iRet2 = DllCall("user32.dll", "lresult", "SendMessageTimeoutW", "hwnd", 0xffff, "dword", 0x001A, "ptr", 0, _
            "wstr", "Environment", "dword", 0x0002, "dword", 5000, "dword_ptr*", 0)
    If $iRet2[0] = 0 Then Return SetError(2, 0, 0)

    Return 1
EndFunc   ;==>_SetComputerName

ReturnToContents

_SetEnvironment

Author: MrCreatoR




Modified: guinness





_SetEnvironment("CUSTOM_PATH", @ScriptDir, 0)

; #FUNCTION# ====================================================================================================================
; Name ..........: _SetEnvironment
; Description ...: Set/update a system wide environment variable.
; Syntax ........: _SetEnvironment($sEnvironmentVar, $sData[, $iAllUsers = 0])
; Parameters ....: $sEnvironmentVar     - Name of the environment variable to set/update.
;                  $sData               - Value to set the environment variable to. If a value is not used the environment variable will be deleted.
;                  $iAllUsers           - [optional] Add to Current Users (0) or All Users (1). Default is 0.
; Return values .: None
; Author ........: MrCreatoR
; Modified ......: guinness
; Link ..........: http://www.autoitscript.com/forum/topic/...can-i-create-a-new-environment
; Example .......: Yes
; ===============================================================================================================================
Func _SetEnvironment($sEnvironmentVar, $sData, $iAllUsers = 0)
    Local $i64Bit = "", $sRegistryKey = ""

    If StringStripWS($sEnvironmentVar, 8) = "" Then
        Return SetError(1, 0, 0)
    EndIf

    If @OSArch = "X64" Then
        $i64Bit = "64"
    EndIf
    If $iAllUsers Then
        $sRegistryKey = "HKEY_LOCAL_MACHINE" & $i64Bit & "\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
    Else
        $sRegistryKey = "HKEY_CURRENT_USER" & $i64Bit & "\Environment"
    EndIf

    If StringStripWS($sData, 8) = "" Then
        Return RegDelete($sRegistryKey, $sEnvironmentVar)
    Else
        Return RegWrite($sRegistryKey, $sEnvironmentVar, "REG_SZ", $sData)
    EndIf
EndFunc   ;==>_SetEnvironment

ReturnToContents

_UUIDCreate

Author: smashly








; Generate a Uuid (Unique user id), I use when I want to generate a dynamic unused CLSID

#include <WinAPI.au3>

Local $sCLSID = _UUIDCreate()
ConsoleWrite($sCLSID & @LF)

Func _UUIDCreate()
	Local $tGUID, $pGUID
	$tGUID = DllStructCreate($tagGUID)
	$pGUID = DllStructGetPtr($tGUID)
	DllCall("rpcrt4.dll", "int", "UuidCreate", "ptr", $pGUID)
	If Not @error Then Return _WinAPI_StringFromGUID($pGUID)
EndFunc   ;==>_UUIDCreate

ReturnToContents

UUID Generator

Author: GaryFrost








;UUID Generator

Const $ERROR_SUCCESS = 0
Const $RPC_S_OK = $ERROR_SUCCESS
Const $RPC_S_UUID_LOCAL_ONLY = 1824
Const $RPC_S_UUID_NO_ADDRESS = 1739

;~ typedef struct _GUID {
;~ unsigned long Data1;
;~ unsigned short Data2;
;~ unsigned short Data3;
;~ unsigned char Data4[8];
;~ } GUID, UUID;
;~ Data1
;~ Specifies the first 8 hexadecimal digits of the UUID.
;~ Data2
;~ Specifies the first group of 4 hexadecimal digits of the UUID.
;~ Data3
;~ Specifies the second group of 4 hexadecimal digits of the UUID.
;~ Data4
;~ Array of eight elements. The first two elements contain the third group of 4 hexadecimal digits of the UUID.
;~ The remaining six elements contain the final 12 hexadecimal digits of the UUID.

Local $_GUID = DllStructCreate("uint;ushort;ushort;ubyte[8]")
If @error Then Exit

;~ RPC_STATUS RPC_ENTRY UuidCreate(
;~ UUID __RPC_FAR* Uuid
;~ );

Local $ret = DllCall("Rpcrt4.dll", "ptr", "UuidCreate", "ptr", DllStructGetPtr($_GUID))
Local $uuid
If Not @error Then
If $ret[0] = $ERROR_SUCCESS Then
  $uuid = Hex(DllStructGetData($_GUID, 1), 8) & "-" & _
    Hex(DllStructGetData($_GUID, 2), 4) & "-" & _
    Hex(DllStructGetData($_GUID, 3), 4) & "-" & _
    Hex(DllStructGetData($_GUID, 4, 1), 2) & Hex(DllStructGetData($_GUID, 4, 2), 2) & "-"
  For $x = 3 To 8
 $uuid = $uuid & Hex(DllStructGetData($_GUID, 4, $x), 2)
  Next
  MsgBox(0,"UUID", $uuid & @LF & @LF & "Note:" & @LF & _
   "In Windows NT 4.0, Windows Me/98, and Windows 95 DCOM release," & @LF & _
   "UuidCreate returns RPC_S_UUID_LOCAL_ONLY when the originating computer" & @LF & _
   "does not have an ethernet/token ring (IEEE 802.x) address." & @LF & _
   "In this case, the generated UUID is a valid identifier, and is" & @LF & _
   "guaranteed to be unique among all UUIDs generated on the computer." & @LF & @LF & _
   "However, the possibility exists that another computer without an" & @LF & _
   "ethernet/token ring address generated the identical UUID." & @LF & @LF & _
   "Therefore you should never use this UUID to identify an object" & @LF & _
   "that is not strictly local to your computer." & @LF & @LF & _
   "Computers with ethernet/token ring addresses generate UUIDs that" & @LF & _
   "are guaranteed to be globally unique.")
EndIf
EndIf
$_GUID = 0

ReturnToContents

_WinShowHide

Author: knightz93








Run("notepad.exe")
Global $hwnd = WinWait("[CLASS:Notepad]", "")

ConsoleWrite('!> HIDE SHOW NOTEPAD WINDOW : ')
ConsoleWrite(WinShowHide($hwnd) & @CRLF)

Sleep(2000)

ConsoleWrite('!> SHOW HIDE NOTEPAD WINDOW :')
ConsoleWrite(WinShowHide($hwnd) & @CRLF)

Sleep(2000)

WinKill("[CLASS:Notepad]", "")

Func WinShowHide($WindowTitle, $WindowText = '')
     Local $Result = WinGetState($WindowTitle, $WindowText)
     If BitAND($Result , 2) = 2 Then
           WinSetState($WindowTitle, $WindowText, @SW_HIDE)
           Return True
     ElseIf BitAND($Result , 2) = 0 Then
           If BitAND($Result , 1) = 0 Then
                Return False
           Else
                WinSetState($WindowTitle, $WindowText, @SW_SHOW)
                Return True
           EndIf
    EndIf
EndFunc

ReturnToContents

_WindowsUpdate

Author: guinness








ConsoleWrite('Windows Update PID: ' & _WindowsUpdate() & @CRLF)

; Version: 1.00. AutoIt: V3.3.8.1
; Start the Windows Update process and detect updates immediately.
Func _WindowsUpdate()
    Return Run(@ComSpec & ' /c wuauclt /a /DetectNow', @SystemDir, @SW_HIDE)
EndFunc   ;==>_WindowsUpdate

ReturnToContents