Snippets ( Windows OS )

From AutoIt Wiki
Jump to navigation Jump to search

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


_CancelPrinterJobs()

Author: guinness








; Cancel printer jobs for the default printer or the printer name provided.

ConsoleWrite(_CancelPrinterJobs() & @CRLF)
ConsoleWrite(_CancelPrinterJobs('HP Printer 1234') & @CRLF)

Func _CancelPrinterJobs($sPrinterName = '')
    If StringStripWS($sPrinterName, 8) = '' Then
        $sPrinterName = 'Default = True'
    Else
        $sPrinterName = 'Name = "' & $sPrinterName & '"'
    EndIf
    Local $iResult = 0, $oWMIService = ObjGet('winmgmts:\\' & '.' & '\root\cimv2')
    Local $oColItems = $oWMIService.ExecQuery('Select * From Win32_Printer Where ' & $sPrinterName)
    If IsObj($oColItems) Then
        For $oObjectItem In $oColItems
            $iResult = $oObjectItem.CancelAllJobs()
        Next
    EndIf
    Return $iResult
EndFunc   ;==>_CancelPrinterJobs

ReturnToContents

_CheckElevationEnabled()

Author: JohnOne








; OS dependent = Vista, server 2008 SP1 and WIN7
;#### Example ####
Local $bUAC = _CheckElevationEnabled()
If @error Then
   Exit MsgBox(0,"Error",@error)
EndIf
MsgBox(0,"UAC Enabled",$bUAC)

;Checks if Use Access Control (UAC) is Enabled.
Func _CheckElevationEnabled()
   Local $struct = DllStructCreate("BOOL")
   Local $aRtn = DllCall("kernel32.dll","DWORD","CheckElevationEnabled","ptr", DllStructGetPtr($struct))
   If @error Then
     Return SetError(@error)
   EndIf
   Return SetError($aRtn[0],0,DllStructGetData($struct,1))
EndFunc

ReturnToContents

_IsDeskTopLocked()

Author: GaryFrost








; Detect if System is Locked

Global Const $DESKTOP_ENUMERATE = 0x40
Global Const $SPI_GETSCREENSAVERRUNNING = 114
Global Const $DESKTOP_SWITCHDESKTOP = 0x100

HotKeySet("{ESC}", "_Terminate")

AdlibEnable("IsDeskTopLocked", 500)

While 1
    Sleep(10)
WEnd

Func _IsDeskTopLocked()
    Local $p_lngHwnd, $p_lngRtn, $p_lngErr, $p_lngScreenSaver, $p_blnIsScreenSaver
   ;~    ' ------------------------------------------
;~    ' First check for screen saver one of 2 ways,
;~    '     based of OS
;~    ' ------------------------------------------
    If @OSTYPE = "WIN32_WINDOWS"  Then
;~       ' ---------------------------------------
;~       ' Pre W2K -- Note, will only be TRUE if
;~       '     the "Password Protected" box is
;~       '     checked.
;~       ' ---------------------------------------
        $p_lngHwnd = DllCall("user32.dll", "int", "OpenDesktopA", "str", "screen-saver", "int", 0, "int", False, "int", $DESKTOP_ENUMERATE)
        If $p_lngHwnd[0] <> 0 Then
            $p_blnIsScreenSaver = True
        Else
            $p_blnIsScreenSaver = False
        EndIf
    Else
;~       ' ---------------------------------------
;~       ' W2K+ -- Will determine if screen saver
;~       '     is running whether or not the
;~       '     "Password Protected" box is checked
;~       ' ---------------------------------------
        $p_lngRtn = DllCall("user32.dll", "int", "SystemParametersInfoA", "int", $SPI_GETSCREENSAVERRUNNING, "int", 0, "int", $p_lngScreenSaver, "int", 0)
        If $p_lngRtn[0] = 0 Then
            ConsoleWrite("Error detecting screen saver" & @LF)
        Else
            $p_blnIsScreenSaver = $p_lngScreenSaver
        EndIf

    EndIf
;~    ' ------------------------------------------
;~    ' If screen saver is *not* running, then
;~    '     check for locked workstation
;~    ' ------------------------------------------
    If $p_blnIsScreenSaver Then
        If @OSTYPE = "WIN32_WINDOWS"  Then
            ConsoleWrite("Screen saver is running..., Handle #" & $p_lngHwnd[0] & @LF)
            $p_lngHwnd = DllCall("user32.dll", "int", "CloseDesktop", "int", $p_lngHwnd[0])
        Else
            ConsoleWrite("Screen saver is running on W2K+" & @LF)
        EndIf
    Else
        $p_lngHwnd = DllCall("user32.dll", "int", "OpenDesktopA", "str", "Default", "int", 0, "int", False, "int", $DESKTOP_SWITCHDESKTOP)

        If $p_lngHwnd[0] = 0 Then
            ConsoleWrite("Error with OpenDesktop" & @LF)
        Else
            $p_lngRtn = DllCall("user32.dll", "int", "SwitchDesktop", "int", $p_lngHwnd[0])
            $p_lngErr = _GetLastErrorMessage()

            If $p_lngRtn[0] = 0 Then
                If $p_lngErr = 0 Then
                    ConsoleWrite("Desktop is locked" & @LF)
                Else
                    ConsoleWrite("Error with SwitchDesktop" & @LF)
                EndIf
            Else
                ConsoleWrite("Not locked!" & @LF)
            EndIf
            $p_lngHwnd = DllCall("user32.dll", "int", "CloseDesktop", "int", $p_lngHwnd[0])
        EndIf
    EndIf
EndFunc   ;==>IsDeskTopLocked

Func _Terminate()
    Exit
EndFunc   ;==>_Terminate
  
;===============================================
;    _GetLastErrorMessage($DisplayMsgBox="")
;    Format the last windows error as a string and return it
;    if $DisplayMsgBox <> "" Then it will display a message box w/ the error
;    Return        Window's error as a string
;===============================================
Func _GetLastErrorMessage($DisplayMsgBox = "")
    Local $ret, $s
    Local $p = DllStructCreate("char[4096]")
    Local Const $FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
    If @error Then Return ""
    $ret = DllCall("Kernel32.dll", "int", "GetLastError")
    $ret = DllCall("kernel32.dll", "int", "FormatMessage", _
            "int", $FORMAT_MESSAGE_FROM_SYSTEM, _
            "ptr", 0, _
            "int", $ret[0], _
            "int", 0, _
            "ptr", DllStructGetPtr($p), _
            "int", 4096, _
            "ptr", 0)
    $s = DllStructGetData($p, 1)
    If $DisplayMsgBox <> "" Then MsgBox(0, "_GetLastErrorMessage", $DisplayMsgBox & @CRLF & $s)
    Return $s
EndFunc   ;==>_GetLastErrorMessage

ReturnToContents

_DisplayWindowsSwitcher()

Author: Knightz93




Modified: guinness





HotKeySet("{ESC}", "_Exit") ; Press the ESC key to escape.

HotKeySet("!3", "_DisplayWindowsSwitcher") ; Press Alt+3 to display the Windows Switcher, though this in Windows is also Win Key + Tab.

While 1
    Sleep(100)
WEnd

; Only works on Windows 7+
Func _DisplayWindowsSwitcher()
    Local $oShell = ObjCreate("shell.application")
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    $oShell.WindowSwitcher()
EndFunc   ;==>_DisplayWindowsSwitcher

Func _Exit()
    Exit
EndFunc   ;==>_Exit

ReturnToContents

_DisableWindowsLock()

Author: guinness








ConsoleWrite('Disable Windows Lock: ' & _DisableWindowsLock() & @CRLF)
MsgBox(4096, '', 'Select Win + L to see the result of using _DisableWindowsLock.')
ConsoleWrite('Disable Windows Lock: ' & _DisableWindowsLock() & @CRLF)

; Disable the locking of Windows. Returns 1 - disabled or 0 - enabled.
Func _DisableWindowsLock()
    Local $i64Bit = ''

    If @OSArch = 'X64' Then
        $i64Bit = '64'
    EndIf
    Local $iRegRead = Number(Not RegRead('HKEY_CURRENT_USER' & $i64Bit & '\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableLockWorkstation'))
    Return SetError(Not RegWrite('HKEY_CURRENT_USER' & $i64Bit & '\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableLockWorkstation', 'REG_DWORD', $iRegRead), 0, $iRegRead)
EndFunc   ;==>_DisableWindowsLock

ReturnToContents

_IsFontExists()

Author: guinness








#include <APIConstants.au3>
#include <WinAPIEx.au3>

ConsoleWrite(_IsFontExists("WebDings.ttf") & @CRLF)

Func _IsFontExists($sFontType)
    Return FileExists(_WinAPI_ShellGetSpecialFolderPath($CSIDL_FONTS) & "\" & $sFontType) ; WebDings.ttf
EndFunc   ;==>_IsFontExists

ReturnToContents

_GetDesktopWallpaper()

Author: guinness








#include <WinAPI.au3>

ConsoleWrite( _GetDesktopWallpaper() & @CRLF)

Func _GetDesktopWallpaper()
    Local $SPI_GETDESKWALLPAPER = 0x0073
    Local $tPATH = DllStructCreate('wchar[260]')
    _WinAPI_SystemParametersInfo($SPI_GETDESKWALLPAPER, 260, DllStructGetPtr($tPATH))
    Return DllStructGetData($tPATH, 1)
EndFunc   ;==>_GetDesktopWallpaper

ReturnToContents

_GetOSVersion()

Author: Xenobiologist








MsgBox(0,0, _GetOSVersion())

Func _GetOSVersion()
    Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    Local $colSettings = $objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
    For $objOperatingSystem In $colSettings
        Return "Windows " & StringMid($objOperatingSystem.Caption, 19)
    Next
EndFunc   ;==>_getOSVersion

ReturnToContents

_InstallDate()

Author: guinness








ConsoleWrite(_InstallDate() & @CRLF)

Func _InstallDate()
    Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2")
    Local $oColFiles = $oWMIService.ExecQuery("Select * From Win32_OperatingSystem")
    If IsObj($oColFiles) Then
        For $oObjectFile In $oColFiles
            Return StringRegExpReplace($oObjectFile.InstallDate, "\A(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:.*)", "$3/$2/$1 $4:$5:$6")
        Next
    EndIf
    Return SetError(1, 0, 0)
EndFunc   ;==>_InstallDate

ReturnToContents

Installed version of Windows with mathematical operators

Author: GEOSoft








 
; Test the installed version of Windows with mathematical operators.

Global Const $2K_VER = 5.0
Global Const $XP_VER = 5.1
Global Const $XP64_VER = 5.2
Global Const $VISTA_VER = 6.0
Global Const $W7_VER = 6.1

$iCurrVer = RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion")
MsgBox(0, "Result", $iCurrVer >= $VISTA_VER)

Return To Contents

_IsElevationRequired()

Author: JohnOne








; OS dependent = Vista, server 2008 SP1 and WIN7 
;#### Example 1 ####
Global $bool = _IsElevationRequired("C:\Windows\notepad.exe") ;Pass path of an exe that does not normally need elevated privileges
If @error Then
   Exit MsgBox(0,"Error",@error)
EndIf
;should show 0
MsgBox(0,"Elevation notepad",$bool)

;#### Example 2 ####
$bool = _IsElevationRequired("C:\Windows\regedit.exe") ;Pass path of an exe that does normally need elevated privileges
If @error Then
   Exit MsgBox(0,"Error",@error)
EndIf
;should show 1
MsgBox(0,"Elevation regedit",$bool)

Func _IsElevationRequired($szPath) ;Checks if an executable (.exe) needs elevated permissions to run.
   Local Const $BAD_ARG = 6
   If StringRight($szPath,3) <> "exe" Then
      Return SetError($BAD_ARG)
   EndIf
   Local $aRtn = DllCall("shell32.dll","BOOL",865,"wstr",$szPath)
   If @error Then
      Return SetError(@error)
   EndIf
   Return $aRtn[0]
EndFunc ;===>_IsElevationRequired

Return To Contents

_IsServer()

Author: guinness








ConsoleWrite( _IsServer() & @CRLF)

Func _IsServer() ; MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239(v=vs.85).aspx
    Local $oWMIService = ObjGet("winmgmts://./root/cimv2"), $oWMIServiceItem
    Local $oColItems = $oWMIService.ExecQuery("Select * From Win32_OperatingSystem")
    If IsObj($oColItems) Then
        For $oWMIServiceItem In $oColItems
            If $oWMIServiceItem.ProductType = 2 Or $oWMIServiceItem.ProductType = 3 Then
                Return 1
            EndIf
        Next
    EndIf
    Return SetError(1, 0, 0)
EndFunc   ;==>_IsServer

Return To Contents

_IsPrimaryOS()

Author: guinness








; Tell if the current OS is the primary OS.

ConsoleWrite("_IsPrimaryOS() >> " & _IsPrimaryOS() & @LF)

Func _IsPrimaryOS($sComputerName = @ComputerName)
    Local $oColItems, $oWMIService

    $oWMIService = ObjGet("winmgmts:\\" & $sComputerName & "\root\cimv2")
    If @error Then
        Return SetError(1, 0, 1)
    EndIf
    $oColItems = $oWMIService.ExecQuery("Select * From Win32_SystemOperatingSystem", "WQL", 0x30)
    If IsObj($oColItems) Then
        For $oObjectItem In $oColItems
            Return $oObjectItem.PrimaryOS
        Next
    EndIf
    Return SetError(1, 0, 1)
EndFunc   ;==>_IsPrimaryOS

Return To Contents

_IsSafeMode()

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

ConsoleWrite(_IsSafeMode() & @CRLF)

Func _IsSafeMode()
    Return _WinAPI_GetSystemMetrics($SM_CLEANBOOT) > 0
EndFunc   ;==>_IsSafeMode

Return To Contents

_IsVirtualMachine()

Author: guinness








ConsoleWrite( _IsVirtualMachine() & @LF)

Func _IsVirtualMachine() ; Returns True or False.
    Local $oColItems, $oWMIService
    $oWMIService = ObjGet("winmgmts:\\localhost\root\cimv2")
    $oColItems = $oWMIService.ExecQuery("Select * From Win32_ComputerSystemProduct", "WQL", 0x30)
    If IsObj($oColItems) Then
        For $oObjectItem In $oColItems
            Return StringRegExp($oObjectItem.Name, 'VirtualBox|VMWare|Virtual PC') = 1
        Next
    EndIf
    Return False
EndFunc   ;==>_IsVirtualMachine

Return To Contents

_IsVistaAbove()

Author: guinness








ConsoleWrite(_IsVistaAbove() & @CRLF) ; Returns True is greater or equal to Windows Vista.

Func _IsVistaAbove()
    Return RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\", "CurrentVersion") >= 6.0
EndFunc   ;==>_IsVistaAbove

Return To Contents

_IsWindowsTablet()

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

MsgBox(64, "_IsWindowsTablet()", _IsWindowsTablet())

Func _IsWindowsTablet()
    Return _WinAPI_GetSystemMetrics($SM_TABLETPC) > 0
EndFunc   ;==>_IsWindowsTablet

Return To Contents

_OSArch()

Author: guinness








#cs
    If you're using Windows x86 then '' is returned otherwise if you're using x64 then '64' is returned.
#ce
ConsoleWrite("Program" & _OSArch() & ".exe" & @LF)

Func _OSArch()
    Return StringRegExpReplace(@OSArch, "(?i)x86|\D+", "") ; Thanks to wraithdu.
EndFunc   ;==>_OSArch

Return To Contents

_OSSerial()

Author: guinness








ConsoleWrite(_OSSerial() & @CRLF)

Func _OSSerial()
    Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2")
    Local $oColFiles = $oWMIService.ExecQuery("Select * From Win32_OperatingSystem")
    If IsObj($oColFiles) Then
        For $oObjectFile In $oColFiles
            Return $oObjectFile.SerialNumber
        Next
    EndIf
    Return SetError(1, 0, 0)
EndFunc   ;==>OSSerial

Return To Contents

_OSVersion()

Author: guinness








; Get the OS version number without an API call.

MsgBox(0, "_OSVersion()", _OSVersion())
MsgBox(0, "_OSVersionEx()", _OSVersionEx())

Func _OSVersion()
    Return RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\", "CurrentVersion")
EndFunc   ;==>_OSVersion

Func _OSVersionEx()
    Return StringLeft(FileGetVersion(@SystemDir & "\WinVer.exe"), 3)
EndFunc   ;==>_OSVersionEx

Return To Contents

_ProcessCloseFromPath()

Author: guinness








#include <MsgBoxConstants.au3>

Example()

Func Example()
	; Close a process using the filepath rather than the filename, which is what ProcessClose requires.

	; Run Notepad
	Run("notepad.exe")

	; Wait 10 seconds for the Notepad window to appear.
	WinWait("[CLASS:Notepad]", "", 10)

	; Wait for 2 seconds.
	Sleep(2000)

	Local $sNotepad = @SystemDir & "\notepad.exe"
	MsgBox($MB_SYSTEMMODAL, "", "Path of Notepad: " & $sNotepad)

	; Close the Notepad process using the filepath.
	_ProcessCloseFromPath($sNotepad)
EndFunc   ;==>Example

Func _ProcessCloseFromPath($sFilePath)
	Return FileExists($sFilePath) ? ProcessClose(StringTrimLeft($sFilePath, StringInStr($sFilePath, "\", Default, -1))) : SetError(1, 0, 0)
EndFunc   ;==>_ProcessCloseFromPath

Return To Contents

_UnDockPC()

Author: guinness








ConsoleWrite(_UnDockPC() & @CRLF)

; Ejects the computer from its docking station.
Func _UnDockPC()
    Local $oShell = ObjCreate('shell.application')
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    $oShell.EjectPC()
    Return 1
EndFunc   ;==>_UnDockPC

Return To Contents

_WMPlayer_Location()

Author: guinness








; Get the location of Windows Media Player.

#include <WinAPI.au3>

ConsoleWrite(_WMPLayer_Location() & @CRLF)

Func _WMPlayer_Location()
    Local $aReturn = StringRegExp(_WinAPI_ExpandEnvironmentStrings(RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\wmplayer.exe\shell\open\command", "")), '(?s)(?i)"(.*?)"', 3)
    If @error Then
        Return SetError(1, 0, "")
    EndIf
    Return $aReturn[0]
EndFunc   ;==>_WMPlayer_Location

Return To Contents