Jump to content

Useful Snippets Collection Thread


KaFu
 Share

Recommended Posts

Just thought about how to store the little bits and pieces I stumble over, so I decided to collect them in this "Useful snippets Collection Thread", ready to be found via the forum search :graduated:.

1. Set FileOpenDialog, FileSaveDialog or FileSelectFolder topmost

I wondered how to set these standard dialog topmost. Turns out it's quite easy by using a topmost dummy GUI as parent without displaying it.

; Not topmost
FileOpenDialog("FileOpenDialog", @ScriptDir, "All (*.*)", 1 + 4, "")
FileSaveDialog("FileSaveDialog", @ScriptDir, "All (*.*)", 2, "")
FileSelectFolder("Choose a folder.", "", 7, @ScriptDir)
; Topmost
#include <windowsconstants.au3>
$hGUI = GUICreate("$WS_EX_TOPMOST", Default, Default, Default, Default, Default, $WS_EX_TOPMOST)
FileOpenDialog("FileOpenDialog", @ScriptDir, "All (*.*)", 1 + 4, "", $hGUI)
FileSaveDialog("FileSaveDialog", @ScriptDir, "All (*.*)", 2, "", $hGUI)
FileSelectFolder("Choose a folder.", "", 7, @ScriptDir, $hGUI)

; Another method provided by guinness
FileOpenDialog("FileOpenDialog", @ScriptDir, "All (*.*)", 1 + 4, "", _OnTop())
FileSaveDialog("FileSaveDialog", @ScriptDir, "All (*.*)", 2, "", _OnTop())
FileSelectFolder("Choose a folder.", "", 7, @ScriptDir, _OnTop())
Func _OnTop()
    Local $sHandle = WinGetHandle(AutoItWinGetTitle())
    WinSetOnTop($sHandle, "", 1)
    Return $sHandle
EndFunc   ;==>_OnTop

2. Change TabStop Order of Controls

To change the TabStop ($WS_TABSTOP) Order of controls you have to change their respective Z-Order.

#include <guiconstantsex.au3>

#include <winapi.au3>
#include <constants.au3>

GUICreate("My GUI", 120, 160)

$c_Input1 = GUICtrlCreateInput("", 10, 10, 100)
$c_Input2 = GUICtrlCreateInput("", 10, 50, 100)
$c_Input3 = GUICtrlCreateInput("", 10, 90, 100)
$c_Input4 = GUICtrlCreateInput("", 10, 130, 100)

GUISetState(@SW_SHOW)

While 1
    $msg = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Then ExitLoop
WEnd

_WinAPI_SetWindowPos(GUICtrlGetHandle($c_Input1), GUICtrlGetHandle($c_Input2), 0, 0, 0, 0, BitOR($SWP_NOSIZE, $SWP_NOMOVE, $SWP_NOACTIVATE))
_WinAPI_SetWindowPos(GUICtrlGetHandle($c_Input3), GUICtrlGetHandle($c_Input4), 0, 0, 0, 0, BitOR($SWP_NOSIZE, $SWP_NOMOVE, $SWP_NOACTIVATE))

While 1
    $msg = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Then ExitLoop
WEnd

GUIDelete()

3. Set Position and change font _GUICtrlComboBoxEx() of controls

A small example on two _GUICtrlComboBoxEx issues I didn't found an answer to in the help-file or on the board, how to set the control position and how to change the control font. Espc. note that the height of the dropdown is defined during control creation. I set it to 17 and wondered why I couldn't see a dropdown. The height of the control itself is derived from the used font (see font change #1 and #2). The font objects should be deleted on exit, because they're needed to redraw the control if you change the selection (see how changing the selection after font change #2 suddenly changes font size again).

#cs ----------------------------------------------------------------------------

    AutoIt Version: 3.3.6.1
    Author:      KaFu

    Script Function:
    _GUICtrlComboBoxEx examples for positioning and set font

#ce ----------------------------------------------------------------------------

#include <guicomboboxex.au3>
#include <constants.au3>
#include <guiconstantsex.au3>
#include <winapi.au3>
#include <fontconstants.au3>

OnAutoItExitRegister("_Delete_Font_Objects")

$hGUI = GUICreate("ComboBoxEx Create", 400, 300)
$hCombo = _GUICtrlComboBoxEx_Create($hGUI, "This is a test|Line 2", 2, 2, 394, 268)
$cCombo = _WinAPI_GetWindowLong($hCombo, $GWL_ID)
consolewrite("Combo ctrlID: " & $cCombo & @crlf)
_GUICtrlComboBoxEx_AddString($hCombo, "Some More Text")
_GUICtrlComboBoxEx_InsertString($hCombo, "Inserted Text", 1)
_GUICtrlComboBoxEx_SetCurSel($hCombo, 0)
GUISetState()

; How to set position of _GUICtrlComboBoxEx
Sleep(2000)
_WinAPI_SetWindowPos($hCombo, $HWND_TOPMOST, 2, 100, 394, 268, $SWP_NOZORDER)

; How to change font of _GUICtrlComboBoxEx
Sleep(2000)
$hFont1 = _WinAPI_CreateFont(40, 0, 0, 0, 800, False, False, False, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, _
        $CLIP_DEFAULT_PRECIS, $PROOF_QUALITY, 0, "Arial")
_WinAPI_SetFont($hCombo, $hFont1, True)

Sleep(2000)
$hFont2 = _WinAPI_CreateFont(10, 0, 0, 0, 800, False, False, False, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, _
        $CLIP_DEFAULT_PRECIS, $PROOF_QUALITY, 0, "Arial")
_WinAPI_SetFont($hCombo, $hFont2, True)
_WinAPI_DeleteObject($hFont2)

Sleep(2000)
_GUICtrlComboBoxEx_SetCurSel($hCombo, 1)

; Loop until user exits
Do
Until GUIGetMsg() = $GUI_EVENT_CLOSE

Func _Delete_Font_Objects()
    _WinAPI_DeleteObject($hFont1)
EndFunc   ;==>_Delete_Font_Object

4. Internet Explorer UDF: Toggle Javascript

Seems to be quite complex. As I read it, you'll have to tweak the zone definition.

http://support.microsoft.com/default.aspx?scid=KB;en-us;q182569

The easiest way seems to be to assign a site with the domain switch to zone 4 (Restricted Sites Zone).

#include <ie.au3>
$sURL = "internet.com"
RegWrite("HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZoneMapDomains" & $sURL, "http", "REG_DWORD", 4)
$oIE = _IECreate("http://javascript.internet.com/games/button-mania.html")
RegDelete("HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZoneMapDomains" & $sURL, "http")

Another method would be to edit the zones themselves:

[HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZonesX

Where X is the number from 0 to 4 representing the security zones.

Set:

1400 Scripting: Active scripting

1402 Scripting: Scripting of Java applets

to 3 which means disable.

5. Internet Explorer UDF: Disable Scrollbars

#include <guiconstantsex.au3>
#include <ie.au3>

$hGUI = GUICreate("", 762, 574)

Global $oIE = _IECreateEmbedded()
Global $hIE = GUICtrlCreateObj($oIE, 10, 10, 742, 554)
_IENavigate($oIE, "http://www.yahoo.com")
$oIE.document.body.scroll = "no"
$oIE.document.body.style.border = "0px"

GUISetState()

While 1
    $iMsg = GUIGetMsg()
    Switch $iMsg
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

6. Internet Explorer UDF: Re-Enable Basic Authentication URL Syntax

; http://support.microsoft.com/kb/834489
#include <ie.au3>
RegWrite("HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMainFeatureControlFEATURE_HTTP_USERNAME_PASSWORD_DISABLE","iexplore.exe","REG_DWORD",0)
_IECreate ("http://USERNAME:PASSWORD@website.com/protected_dir/")
RegWrite("HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMainFeatureControlFEATURE_HTTP_USERNAME_PASSWORD_DISABLE","iexplore.exe","REG_DWORD",1)

7. Create big empty files

#include <constants.au3>
Local Const $sFile = "test.txt"
Local $hFile = FileOpen($sFile, 2)
; Check if file opened for writing OK
If $hFile = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf
FileSetPos($hFile, (1024*1024*100)-1, $FILE_BEGIN)
FileWrite($hFile, 0)
; Close the handle.
FileClose($hFile)

8. Facts on UAC

#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator

Microsoft recommends that all executables, such as Setup programs (which need access to protected areas of Windows), should be marked as requireAdministrator. This will always result in an UAC prompt on program start.

#AutoIt3Wrapper_Res_requestedExecutionLevel=highestAvailable

If you are Admin, the program will run as Admin and prompt an UAC request.

#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker

Program will run without an UAC request even if you are Admin. This might lead to UAC issues, e.g. you can not access the HKEY_LOCAL_MACHINE registry hive, you can not change or delete files with higher authorizations needed.

There are a number of ways to elevate the execution level of an executable:

  • Right-click an EXE or its shortcut and select "Run as administrator" from the context menu.
  • Right-click and select properties. Click the advanced button (General Tab) and check the "Run as administrator" checkbox.
  • Right-click and select properties. Click the "Show Settings for all users" (Compatibility Tab) and check the "Run as administrator" checkbox.
  • Login as a real Administrator and run from there (Don't do this. Not secure).
The system behavior regarding UAC requests can be read from the registry:

; http://technet.microsoft.com/en-us/library/dd835564%28WS.10%29.aspx

Global $b_ScriptIsRunningWithAdminRights, $b_UAC_IsEnabled, $s_UAC_BehaviorAdmin, $s_UAC_BehaviorUser, $s_UAC_EnableInstallerDetection

Switch IsAdmin()
    Case 0
        $b_ScriptIsRunningWithAdminRights = False
    Case Else
        $b_ScriptIsRunningWithAdminRights = True
EndSwitch

Switch RegRead("HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem", "EnableLUA")
    Case 0
        $b_UAC_IsEnabled = "UAC (formally known as LUA) is disabled."
    Case 1
        $b_UAC_IsEnabled = "UAC (formally known as LUA) is enabled."
EndSwitch

Switch RegRead("HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem", "ConsentPromptBehaviorAdmin")
    Case 0
        $s_UAC_BehaviorAdmin = "Elevate without prompting (Use this option only in the most constrained environments)"
    Case 1
        $s_UAC_BehaviorAdmin = "Prompt for credentials on the secure desktop"
    Case 2
        $s_UAC_BehaviorAdmin = "Prompt for consent on the secure desktop"
    Case 3
        $s_UAC_BehaviorAdmin = "Prompt for credentials"
    Case 4
        $s_UAC_BehaviorAdmin = "Prompt for consent"
    Case 5
        $s_UAC_BehaviorAdmin = "Prompt for consent for non-Windows binaries (default)"
EndSwitch


Switch RegRead("HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem", "ConsentPromptBehaviorUser")
    Case 0
        $s_UAC_BehaviorUser = "Automatically deny elevation requests"
    Case 1
        $s_UAC_BehaviorUser = "Prompt for credentials on the secure desktop (default)"
    Case 3
        $s_UAC_BehaviorUser = "Prompt for credentials"
EndSwitch

Switch RegRead("HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem", "EnableInstallerDetection")
    Case 0
        $s_UAC_EnableInstallerDetection = "Disabled (default for enterprise)"
    Case 1
        $s_UAC_EnableInstallerDetection = "Enabled (default for home)"
EndSwitch

MsgBox(64 + 262144, "Script Info - " & @UserName, "Script is started by user with Admin rights = " & _IsAdministrator() & @CRLF & _
        "Script is started with Admin access = " & $b_ScriptIsRunningWithAdminRights & @CRLF & @CRLF & _
        "EnableLUA:" & @CRLF & $b_UAC_IsEnabled & @CRLF & @CRLF & _
        "ConsentPromptBehaviorAdmin:" & @CRLF & $s_UAC_BehaviorAdmin & @CRLF & @CRLF & _
        "ConsentPromptBehaviorUser:" & @CRLF & $s_UAC_BehaviorUser & @CRLF & @CRLF & _
        "EnableInstallerDetection:" & @CRLF & $s_UAC_EnableInstallerDetection)

; trancexx
; http://www.autoitscript.com/forum/topic/113611-if-isadmin-not-detected-as-admin/page__view__findpost__p__795036
Func _IsAdministrator($sUser = @UserName, $sCompName = ".")
    Local $aCall = DllCall("netapi32.dll", "long", "NetUserGetInfo", "wstr", $sCompName, "wstr", $sUser, "dword", 1, "ptr*", 0)
    If @error Or $aCall[0] Then Return SetError(1, 0, False)
    Local $fPrivAdmin = DllStructGetData(DllStructCreate("ptr;ptr;dword;dword;ptr;ptr;dword;ptr", $aCall[4]), 4) = 2
    DllCall("netapi32.dll", "long", "NetApiBufferFree", "ptr", $aCall[4])
    Return $fPrivAdmin
EndFunc   ;==>_IsAdministrator

The IsAdmin() function will show you, if the script is running with elevated execution level. Scripts compiled with "asInvoker" will never do so without further actions. IsRunningWithAdminExecutionLevel() would have been a better name.

To detect if an UAC prompt (prompt for consent/credentials) currently exists, look out for the underlying default Windows process "consent.exe".

"Installer Detection" Policy = Automatic Elevation

It turns out that Windows actually examines the names of all executable you run, and if they contain the words "setup", "install", "update", "patch" etc then the executable is automatically elevated; e.g. MySetup001.exe will run elevated. I've heard of cases where a word such as "update" found within an executables resources also trigged elevation. I've also heard that Windows can recognize and elevate setup files created by InstallShield and Wise. I'm not sure of the exact heuristics used.

For more on UAC also take a look at my example of how to

From Windows Vista Application Development Requirements for User Account Control (UAC):

User Interface Privilege Isolation (UIPI)

A lower privilege process cannot:
[*]Perform a window handle validation of higher process privilege.
[*]SendMessage or PostMessage to higher privilege application windows. These Application Programming Interfaces (APIs) return success but silently drop the window message.
[*]Use thread hooks to attach to a higher privilege process.
[*]Use Journal hooks to monitor a higher privilege process.
[*]Perform DLL injection to a higher privilege process.

With UIPI enabled, the following shared USER resources are still shared between processes at different privilege levels:
[*]Desktop window, which actually owns the screen surface.
[*]Desktop heap read-only shared memory.
[*]Global atom table.
[*]Clipboard

If you're creating the process with higher elevation you can use the ChangeWindowMessageFilter function to allow certain messages being posted to you from lower privileged processes.

Edited by KaFu
Link to comment
Share on other sites

  • 2 months later...

For the first Example I use this...It just uses the Internal AutoIt window.

FileOpenDialog("FileOpenDialog", @ScriptDir, "All (*.*)", 1 + 4, "", _OnTop())
FileSaveDialog("FileSaveDialog", @ScriptDir, "All (*.*)", 2, "", _OnTop())
FileSelectFolder("Choose a folder.", "", 7, @ScriptDir, _OnTop())

Func _OnTop()
    Local $hHandle = WinGetHandle(AutoItWinGetTitle())
    WinSetOnTop($hHandle, "", 1)
    Return $hHandle
EndFunc   ;==>__OnTop
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Nice idea again to have a consolidated topic with interesting code snippets but there is already one from Valuater (Sticky Topic ->

I don't know whether he still maintains the topic...

Anyway, I hope you will maintain this topic regularly! :x

Br,

UEZ

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

  • 4 months later...

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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...