
masvil
-
Posts
173 -
Joined
-
Last visited
Reputation Activity
-
masvil reacted to guinness in _FindInFile() - Search for a string within files located in a specific directory.
I've recently been uncovering the useful commandline tools that can be found natively in Windows, one of which was findstr (there is also a GUI interface available in SciTE4AutoIt3.) After coming across this little gem and implementing in >SciTE Jump, it felt only right that I should share this on the forums as a standalone UDF. Thanks
Function:
; #FUNCTION# ==================================================================================================================== ; Name ..........: _FindInFile ; Description ...: Search for a string within files located in a specific directory. ; Syntax ........: _FindInFile($sSearch, $sFilePath[, $sMask = '*'[, $fRecursive = True[, $fLiteral = Default[, ; $fCaseSensitive = Default[, $fDetail = Default]]]]]) ; Parameters ....: $sSearch - The keyword to search for. ; $sFilePath - The folder location of where to search. ; $sMask - [optional] A list of filetype extensions separated with ';' e.g. '*.au3;*.txt'. Default is all files. ; $fRecursive - [optional] Search within subfolders. Default is True. ; $fLiteral - [optional] Use the string as a literal search string. Default is False. ; $fCaseSensitive - [optional] Use Search is case-sensitive searching. Default is False. ; $fDetail - [optional] Show filenames only. Default is False. ; Return values .: Success - Returns a one-dimensional and is made up as follows: ; $aArray[0] = Number of rows ; $aArray[1] = 1st file ; $aArray[n] = nth file ; Failure - Returns an empty array and sets @error to non-zero ; Author ........: guinness ; Remarks .......: For more details: http://ss64.com/nt/findstr.html ; Example .......: Yes ; =============================================================================================================================== Func _FindInFile($sSearch, $sFilePath, $sMask = '*', $fRecursive = True, $fLiteral = Default, $fCaseSensitive = Default, $fDetail = Default) Local $sCaseSensitive = $fCaseSensitive ? '' : '/i', $sDetail = $fDetail ? '/n' : '/m', $sRecursive = ($fRecursive Or $fRecursive = Default) ? '/s' : '' If $fLiteral Then $sSearch = ' /c:' & $sSearch EndIf If $sMask = Default Then $sMask = '*' EndIf $sFilePath = StringRegExpReplace($sFilePath, '[\\/]+$', '') & '\' Local Const $aMask = StringSplit($sMask, ';') Local $iPID = 0, $sOutput = '' For $i = 1 To $aMask[0] $iPID = Run(@ComSpec & ' /c ' & 'findstr ' & $sCaseSensitive & ' ' & $sDetail & ' ' & $sRecursive & ' "' & $sSearch & '" "' & $sFilePath & $aMask[$i] & '"', @SystemDir, @SW_HIDE, $STDOUT_CHILD) ProcessWaitClose($iPID) $sOutput &= StdoutRead($iPID) Next Return StringSplit(StringStripWS(StringStripCR($sOutput), BitOR($STR_STRIPLEADING, $STR_STRIPTRAILING)), @LF) EndFunc ;==>_FindInFileExample use of Function:
#include <Array.au3> #include <Constants.au3> Example() Func Example() Local $hTimer = TimerInit() Local $aArray = _FindInFile('findinfile', @ScriptDir, '*.au3;*.txt') ; Search for 'findinfile' within the @ScripDir and only in .au3 & .txt files. ConsoleWrite(Ceiling(TimerDiff($hTimer) / 1000) & ' second(s)' & @CRLF) _ArrayDisplay($aArray) $hTimer = TimerInit() $aArray = _FindInFile('autoit', @ScriptDir, '*.au3') ; Search for 'autoit' within the @ScripDir and only in .au3 files. ConsoleWrite(Ceiling(TimerDiff($hTimer) / 1000) & ' second(s)' & @CRLF) _ArrayDisplay($aArray) EndFunc ;==>Example -
masvil reacted to Danp2 in WebDriver UDF - Help & Support (II)
As the WebDriver UDF - Help & Support thread has grown too big, I started a new one.
The original thread can be found here.
-
-
masvil reacted to Jon in Display Name Changes
I'm turning off the ability for user's to change their own display names at the end of today. After that you can request a name change from a moderator. Just to prevent confusion, messing about, etc.
-
masvil reacted to FredAI in System restore UDF
Hi.
I needed this for one of my apps, and all I could find here was a WMI object function to create a restore point, so I decided to create this UDF and post it here.
It has functions to enumerate, delete (one or all) and create restore points.
Also enable or disable the system restore, and restore the system to one of the restore points.
There are only two functions available through DllCall on msdn, the others are WMI.
The UDF is not commented yet, I'll do it tomorrow and update. It's getting late, now. Better call it a night.
Sorry for the delay. Here's the commented updated version: (28 downloads before)
Note: Some functions were slightly modified.
Updated 15/11/2011 (66 total downloads). The $DriveL optional parameter in the _SR_Enable and _SR_Disable functions must be in the format $SystemDrive & '\', or the functions won't work.
SystemRestore.au3
-
masvil reacted to Jefrey in CmdLine UDF (get value/existence/flag)
I wrote this very simple functions to parse command line arguments.
It can get:
Simple key/value
Example. The following code:
#include "cmdline.au3" MsgBox(0, _CmdLine_Get('color')) Will return "white" if you run the script in one of these ways (quotes are optional but mandatory if you're going to use spaces):
script.exe -color "white" script.exe --color white script.exe /color white Existence
Example. The following code:
#include "cmdline.au3" If _CmdLine_KeyExists('givemecoffee') Then ConsoleWrite('You want coffee.') Else ConsoleWrite('You do not want coffee.') EndIf Will return "You want coffee." if you run one of these:
script.exe -givemecoffee script.exe --givemecoffee script.exe /givemecoffee And the following code:
#include "cmdline.au3" If _CmdLine_ValueExists('givemecoffee') Then ConsoleWrite('You want coffee.') Else ConsoleWrite('You do not want coffee.') EndIf Will return "You want coffee." if you run one of these:
script.exe givemecoffee script.exe "givemecoffee" Flags
Example. This script:
#include "cmdline.au3" ConsoleWrite("You want: ") If _CmdLine_FlagEnabled('C') Then ConsoleWrite("coffee ") EndIf If _CmdLine_FlagEnabled('B') Then ConsoleWrite("beer ") EndIf ConsoleWrite(" and you do not want: ") If _CmdLine_FlagDisabled('V') Then ConsoleWrite("vodka ") EndIf If _CmdLine_FlagDisabled('W') Then ConsoleWrite("wine ") EndIf ConsoleWrite(" but you did not tell me if you want: ") If Not _CmdLine_FlagExists('S') Then ConsoleWrite("soda ") EndIf If Not _CmdLine_FlagExists('J') Then ConsoleWrite("juice ") EndIf Will return "You want: coffee beer and you do not want: vodka wine but you did not tell me if you want: soda juice" if you run:
script.exe +CB -VW Getting argument by its index
You can also read the $CmdLine (1-based index) through this function. The advantage is that if the index does not exist (the user did not specify the argument), it won't break your script. It will just return the value you specify in the second function parameter.
#include "cmdline.au3" $first_argument = _CmdLine_GetValByIndex(1, False) If Not $first_argument Then ConsoleWrite("You did not specify any argument.") Else ConsoleWrite("First argument is: " & $first_argument) EndIf Just a note: The second value of _CmdLine_GetValByIndex function can be an integer value, a string, a boolean value, an array or anything you want it to return if the index does not exist in $CmdLine array.
This parameter is also available in _CmdLine_Get() function, also as a second function parameter. In this case, it will return this value if the key was not found. Example:
#include "cmdline.au3" $user_wants = _CmdLine_Get("iwant", "nothing") ConsoleWrite("You want " & $user_wants) So, if you run:
script.exe /iwant water It will return "You want water". But if you run just:
script.exe It will return "You want nothing". Please note that, as these two are the only functions in this library meant to return strings, the second parameter is not available for the other functions. By default, if you do not specify any fallback value, it returns null if the wanted value could not be found.
Also, please note that this UDF can NOT parse arguments in the format (key=value). Example:
script.exe key=value IT WILL NOT WORK
Here is the code:
#include-once #comments-start CmdLine small UDF coder: Jefrey (jefrey[at]jefrey.ml) #comments-end Func _CmdLine_Get($sKey, $mDefault = Null) For $i = 1 To $CmdLine[0] If $CmdLine[$i] = "/" & $sKey OR $CmdLine[$i] = "-" & $sKey OR $CmdLine[$i] = "--" & $sKey Then If $CmdLine[0] >= $i+1 Then Return $CmdLine[$i+1] EndIf EndIf Next Return $mDefault EndFunc Func _CmdLine_KeyExists($sKey) For $i = 1 To $CmdLine[0] If $CmdLine[$i] = "/" & $sKey OR $CmdLine[$i] = "-" & $sKey OR $CmdLine[$i] = "--" & $sKey Then Return True EndIf Next Return False EndFunc Func _CmdLine_ValueExists($sValue) For $i = 1 To $CmdLine[0] If $CmdLine[$i] = $sValue Then Return True EndIf Next Return False EndFunc Func _CmdLine_FlagEnabled($sKey) For $i = 1 To $CmdLine[0] If StringRegExp($CmdLine[$i], "\+([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then Return True EndIf Next Return False EndFunc Func _CmdLine_FlagDisabled($sKey) For $i = 1 To $CmdLine[0] If StringRegExp($CmdLine[$i], "\-([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then Return True EndIf Next Return False EndFunc Func _CmdLine_FlagExists($sKey) For $i = 1 To $CmdLine[0] If StringRegExp($CmdLine[$i], "(\+|\-)([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then Return True EndIf Next Return False EndFunc Func _CmdLine_GetValByIndex($iIndex, $mDefault = Null) If $CmdLine[0] >= $iIndex Then Return $CmdLine[$iIndex] Else Return $mDefault EndIf EndFunc -
masvil reacted to Bilgus in Windows Firewall Policy2 Interface UDF, Provides access to the firewall policy for Windows Vista+
; 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:
Test Script:
-
masvil reacted to KaFu in Systray_UDF Problem
Upsa, adjustments made on my heavily customized version ...
Add this to the top of the Systray.au3
Global $__hWnd_Shell_TrayWnd = DllCall("user32.dll", "hwnd", "FindWindow", "str", "Shell_TrayWnd", "ptr", 0) $__hWnd_Shell_TrayWnd = $__hWnd_Shell_TrayWnd[0] and this
DllCall("user32.dll", "int", "SendMessageW", "hwnd", $__hWnd_Shell_TrayWnd, "uint", 0x001A, "wparam", 0, "lparam", 0) ; $WM_SETTINGCHANGE = 0x001A directly after this call in Func _SysTrayIconRemove(
DLLCall("user32.dll","int","SendMessage", "hwnd", $hWnd, "int", $TB_DELETEBUTTON, "int", $index, "int", 0) -
masvil reacted to Melba23 in Hint/Tray Tip - how to get text
mLipok,
It is not difficult to do - this gets the text from all of the systray icons :
#include <Array.au3> #Include <GuiToolBar.au3> Get_SysTray_IconText() Func Get_SysTray_IconText() ; Find systray handle Local $hSysTray_Handle = ControlGetHandle('[Class:Shell_TrayWnd]', '', '[Class:ToolbarWindow32;Instance:1]') If @error Then MsgBox(16, "Error", "System tray not found") Exit EndIf ; Get systray item count Local $iSysTray_ButCount = _GUICtrlToolbar_ButtonCount($hSysTray_Handle) If $iSysTray_ButCount = 0 Then MsgBox(16, "Error", "No items found in system tray") Exit EndIf Local $aSysTray_ButtonText[$iSysTray_ButCount] ; Look for wanted tooltip For $iSysTray_ButtonNumber = 0 To $iSysTray_ButCount - 1 $aSysTray_ButtonText[$iSysTray_ButtonNumber] = _GUICtrlToolbar_GetButtonText($hSysTray_Handle, $iSysTray_ButtonNumber) Next _ArrayDisplay($aSysTray_ButtonText, "SysTray Icon Text", Default, 8) EndFunc All you need to do is search the text from each button for some permanent text associated with the button you want to interrogate ("Skype" in your case) and just return the text from that button.
M23
-
masvil reacted to mikell in GUI Position minus taskbar height
_WinAPI_GetMonitorInfo returns an array, isn't the $array[1] what you're looking for ?
-
masvil reacted to careca in GUI Position minus taskbar height
This is what i use
#include <Inet.au3> #include <Misc.au3> #include <Timers.au3> #include <WinAPI.au3> #include <Marquee.au3> #include <Constants.au3> #include <WinAPIFiles.au3> #include <FileConstants.au3> #include <ScreenCapture.au3> #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <StructureConstants.au3> #include <WinAPIsysinfoConstants.au3> #include <WinAPISys.au3> #include <WinAPIMisc.au3> #include <APISysConstants.au3> $GWArea = GetWorkArea() $hChildWin = GUICreate("window", @DesktopWidth, $GWArea[0] , -1, -1, $WS_POPUP) GUISetState(@SW_SHOW, $hChildWin) Sleep(3000) Exit Func GetWorkArea() Local $tWorkArea = DllStructCreate($tagRECT) _WinAPI_SystemParametersInfo($SPI_GETWORKAREA, 0, $tWorkArea) Local $aReturn = [DllStructGetData($tWorkArea, 'Bottom') - DllStructGetData($tWorkArea, 'Top')] Return $aReturn EndFunc ;==>GetWorkArea Nevermind the includes, it's just a copy paste i do to make sure it doesnt complain.
-
masvil reacted to mLipok in GUI Position minus taskbar height
Currently AutoIt has:
_WinAPI_GetWorkArea() But ....
@mikell I was working a little with your example, as following:
; #FUNCTION# ==================================================================================================================== ; Name ..........: _Monitor_GetWorkArea ; Description ...: ; Syntax ........: _Monitor_GetWorkArea() ; Parameters ....: $iDPI - [optional] an integer value. Default is -1. ; Return values .: Array ; Author ........: mikell ; Modified ......: mLipok ; Remarks .......: HowTO: WinMove($hGui, "", $aWorkAera[0], $aWorkAera[1], $aWorkAera[4], $aWorkAera[5]) ; Related .......: ; Link ..........: http://www.autoitscript.com/forum/topic/165766-gui-position-minus-taskbar-height/#entry1210698 ; Link ..........: https://docs.microsoft.com/pl-pl/windows/desktop/api/winuser/nf-winuser-systemparametersinfofordpi ; Link ..........: https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-systemparametersinfoa ; Example .......: No ; =============================================================================================================================== Func _Monitor_GetWorkArea($iDPI = -1) Local $tStartRect = DllStructCreate("int[4]") Local $pStartRect = DllStructGetPtr($tStartRect) If $iDPI = -1 Then DllCall("user32.dll", "int", "SystemParametersInfo", "int", $SPI_Monitor_GetWorkArea, "int", 0, "ptr", $pStartRect, "int", 0) Else DllCall("user32.dll", "int", "SystemParametersInfoForDpi", "int", $SPI_Monitor_GetWorkArea, "int", 0, "ptr", $pStartRect, "int", 0, "int", $iDPI) EndIf Local $aArea[6] $aArea[0] = DllStructGetData($tStartRect, 1, 1) $aArea[1] = DllStructGetData($tStartRect, 1, 2) $aArea[2] = DllStructGetData($tStartRect, 1, 3) $aArea[3] = DllStructGetData($tStartRect, 1, 4) $aArea[4] = $aArea[2] - $aArea[0] $aArea[5] = $aArea[3] - $aArea[1] Return $aArea EndFunc ;==>_Monitor_GetWorkArea
I just add support for DPI but not tested yet, and reading here:
https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-systemparametersinfoa
I was wondering how to combine GetMonitorInfo with GetWorkArea ?
I'm trying to combine it all together with:
Do you have idea how to combine GetMonitorInfo with GetWorkArea ?
-
masvil reacted to Ascer in [UDF] Google oAuth 2.0 with AutoIt.
1. Description.
oAuth 2.0 is security system implemented by Google a few years ago. You are able to connect into your Google accounts and manage documents. In this UDF i show you how to pass first authorization process., this allow you to automate most of functions using API interface. 2. Requirements.
Google account. oAuth.au3 Download 3. Possibilities
;============================================================================================================ ; Date: 2018-02-10, 14:21 ; ; Description: UDF for authorize your app with oAuth 2.0 Google. ; ; Function(s): ; oAuth2GetAuthorizationCode() -> Get Code for "grant". ; oAuth2GetAccessToken() -> Get "access_token" and "refresh_token" first time. ; oAuth2RefreshAccessToken() -> Get current "access_token" using "refresh_token". ; ; Author(s): Ascer ;============================================================================================================ 4. Enable your Google API.
4.1. Video Tutorial not mine!
YouTube 4.2 Screenshots from authorization process (Polish language)
Go to https://console.developers.google.com/apis/dashboard and accept current rules.
Next create an new project
Enter name of you new project and click Create
Google will working now, please wait until finish. Next go to enable your API interface, we make if for Google
Take "Gmail" in search input and after click in found result.
Click Enable interface, Google will working now.
Create your login credentials
Select Windows Interface (combobox), User credentials (radio) and click button what is need bla bla
Type name of a new client id for oAuth 2.0 and click Create a new Client ID.
Next configure screen aplication, type some name and click Next. Google will working now.
Last step on this website is download source with your credentials in *Json format.
Now you received a file named client_id.json, it's how it look in Sublime Text:
5. Coding.
Now we need to call a some function to get access code.
#include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sRedirectUri = "http://localhost" oAuth2GetAuthorizationCode($sClientId, $sRedirectUri)
Function will execute default browser for ask you to permission.
Next Google ask you to permission for access to your personal details by application Autoit
Now you can thing is something wrong but all is ok, you need to copy all after code= . It your access code.
Let's now ask Google about our Access Token and Refresh Token
#include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sAuthorizationCode = "4/AAAPXJOZ-Tz0s6mrx7JbV6nthXSfcxaszFh_aH0azVqHkSHkfiwE8uamcabn4eMbEWg1eAuUw7AU0PQ0XeWUFRo#" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2GetAccessToken($sClientId, $sClientSecret, $sAuthorizationCode, $sRedirectUri) If Ubound($aRet) <> 4 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("refresh_token: " & $aRet[2] & @CRLF) ConsoleWrite("token_type: " & $aRet[3] & @CRLF)
Important! When you received error 400 and output says: Invalid grant it means that your previous generated access_code lost validity and you need to generate new calling previus code. When everything is fine you should received a 4 informations about your: access_token, expires_in, refresh_token and token_type. Access_Token time is a little short so you need to know fuction possible to refresh it (tell Google that he should generate a new Token for you)
#include <oAuth.au3> Local $sRefreshToken = "1/ba8JpW7TjQH3-UI1BvPaXhSf-oTQ4BmZAbBfhcKgKfY" Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2RefreshAccessToken($sRefreshToken, $sClientId, $sClientSecret) If Ubound($aRet) <> 3 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("token_type: " & $aRet[2] & @CRLF)
6. Finish words
If you followed all this above steps im sure that you received all informations required for coding your Google API (Gmail, Dropbox, YouTube, Calender etc. See next thread: [UDF] Gmail API - Email automation with AutoIt! -
masvil reacted to ISI360 in ISN AutoIt Studio
Hi!
Thanks for your feedback, and welcome to ISN
About the fileextenstions: Yeah i know there are some problemes and i had to readjust that. It´s on the To-Do List...
And the parameter Editor: This error message appears because the command is not finished. So GuiCreate() for example should work.
-
masvil reacted to mLipok in _StringToPDF
@esneyder
Using PDFCreator you can convert RTF to PDF
You can also convert RTF > PDF using OOO
And it would be the fastest, easies, and the cheapest solution.
Finally you can use QuickPDF UDF (free) + ActiveX DLL (commercial == paid software) and using this you will be able to make PDF from scratch, without RTF / PDFCreatore / OOO
You can also do the same using MPDF.au3 UDF
To all this solution (excluding OOO) you was pointed above.
If you have further problems you can ask more questions.
-
masvil reacted to TheSaint in Ini in memory
Hello masvil, look at the last post date .... from 2008. AutoIt has changed a lot since then, so there could well be compatibility issues.
So you have revived an essentially dead topic, which is called necro posting ... and seriously frowned upon here.
The acceptable procedure, is to start a new topic of your own, and then if necessary, link back to the dead topic.
That's if it is at all relevant to do so, considering the age of the code.
-
masvil reacted to Danyfirex in Using Cmd to launch website via Edge
Other alternative...
Run(@ComSpec & " /c start microsoft-edge:https://google.com","",@SW_HIDE) Saludos
-
masvil reacted to Jos in _SelfDelete() - Delete the running executable.
Don't forget we need some sort of compatibility for all used OSes.
Jos
-
masvil reacted to guinness in _SelfDelete() - Delete the running executable.
Having used the _SelfDelete() function before, I knew it could be improved upon with adding more functionality to compensate for when an AutoIt error might occur.
The version I updated includes the ability to monitor when the process is closed and/or the timer is reached, therefore if an error was to occur with your program and the _SelfDelete() function was called before, it will still delete the executable even with an AutoIt error (due to bad coding of course!) This can't be said for the old version of _SelfDelete() as you'll never have chance to call the function! I also included the option to check either the process name or PID, depending on your preference. Thanks.
Function: Using a Batch script. Save as _SelfDelete.au3
#include-once #include <FileConstants.au3> #include <StringConstants.au3> ; #FUNCTION# ==================================================================================================================== ; Name ..........: _SelfDelete ; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached. ; Syntax ........: _SelfDelete([$iDelay = 5[, $fUsePID = False[, $fRemoveDir = False]]]) ; Parameters ....: $iDelay - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable. ; If 0 is specified then the batch will wait indefinitely until the process no longer exits. Default is 5 (seconds). ; $fUsePID - [optional] Use the process name (False) or PID (True). Default is False. ; $fRemoveDir - [optional] Remove the script directory as well (True) or only the running executable (False). Default is False. ; Return values .: Success - Returns the PID of the batch file. ; Failure - Returns 0 & sets @error to non-zero ; Author ........: guinness ; Modified ......: ; Remarks .......: The idea for removing the directory came from: http://www.autoitscript.com/forum/topic/137287-delete-scriptdir/ ; Example .......: Yes ; =============================================================================================================================== Func _SelfDelete($iDelay = 5, $fUsePID = Default, $fRemoveDir = Default) If @Compiled = 0 Then Return SetError(1, 0, 0) EndIf Local $sTempFileName = @ScriptName $sTempFileName = StringLeft($sTempFileName, StringInStr($sTempFileName, '.', $STR_NOCASESENSEBASIC, -1) - 1) While FileExists(@TempDir & '\' & $sTempFileName & '.bat') $sTempFileName &= Chr(Random(65, 122, 1)) WEnd $sTempFileName = @TempDir & '\' & $sTempFileName & '.bat' Local $sDelay = '' $iDelay = Int($iDelay) If $iDelay > 0 Then $sDelay = 'IF %TIMER% GTR ' & $iDelay & ' GOTO DELETE' EndIf Local $sRemoveDir = '' If $fRemoveDir Then $sRemoveDir = 'RD /S /Q "' & FileGetShortName(@ScriptDir) & '"' & @CRLF EndIf Local $sAppID = @ScriptName, $sImageName = 'IMAGENAME' If $fUsePID Then $sAppID = @AutoItPID $sImageName = 'PID' EndIf Local Const $iInternalDelay = 2, _ $sScriptPath = FileGetShortName(@ScriptFullPath) Local Const $sData = 'SET TIMER=0' & @CRLF _ & ':START' & @CRLF _ & 'PING -n ' & $iInternalDelay & ' 127.0.0.1 > nul' & @CRLF _ & $sDelay & @CRLF _ & 'SET /A TIMER+=1' & @CRLF _ & @CRLF _ & 'TASKLIST /NH /FI "' & $sImageName & ' EQ ' & $sAppID & '" | FIND /I "' & $sAppID & '" >nul && GOTO START' & @CRLF _ & 'GOTO DELETE' & @CRLF _ & @CRLF _ & ':DELETE' & @CRLF _ & 'TASKKILL /F /FI "' & $sImageName & ' EQ ' & $sAppID & '"' & @CRLF _ & 'DEL "' & $sScriptPath & '"' & @CRLF _ & 'IF EXIST "' & $sScriptPath & '" GOTO DELETE' & @CRLF _ & $sRemoveDir _ & 'GOTO END' & @CRLF _ & @CRLF _ & ':END' & @CRLF _ & 'DEL "' & $sTempFileName & '"' Local Const $hFileOpen = FileOpen($sTempFileName, $FO_OVERWRITE) If $hFileOpen = -1 Then Return SetError(2, 0, 0) EndIf FileWrite($hFileOpen, $sData) FileClose($hFileOpen) Return Run($sTempFileName, @TempDir, @SW_HIDE) EndFunc ;==>_SelfDeleteFunction: Using a VBScript file. Save as _SelfDelete.au3
#include-once #include <FileConstants.au3> #include <StringConstants.au3> ; #FUNCTION# ==================================================================================================================== ; Name ..........: _SelfDelete ; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached. ; Syntax ........: _SelfDelete([$iDelay = 5[, $fUsePID = False[, $fRemoveDir = False]]]) ; Parameters ....: $iDelay - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable. ; If 0 is specified then the script will wait indefinitely until the process no longer exits. Default is 5 (seconds). ; $fUsePID - [optional] Use the process name (False) or PID (True). Default is False. ; $fRemoveDir - [optional] Remove the script directory as well (True) or only the running executable (False). Default is False. ; Return values .: Success - Returns the PID of the batch file. ; Failure - Returns 0 & sets @error to non-zero ; Author ........: guinness ; Modified ......: ; Remarks .......: The idea for removing the directory came from: http://www.autoitscript.com/forum/topic/137287-delete-scriptdir/ ; Example .......: Yes ; =============================================================================================================================== Func _SelfDelete($iDelay = 5, $fUsePID = Default, $fRemoveDir = Default) If @Compiled = 0 Then Return SetError(1, 0, False) EndIf Local $sTempFileName = @ScriptName $sTempFileName = StringLeft($sTempFileName, StringInStr($sTempFileName, '.', $STR_NOCASESENSEBASIC, -1) - 1) While FileExists(@TempDir & '\' & $sTempFileName & '.bat') $sTempFileName &= Chr(Random(65, 122, 1)) WEnd $sTempFileName = @TempDir & '\' & $sTempFileName & '.vbs' Local $sDelay = '' $iDelay = Int($iDelay) If $iDelay > 0 Then $sDelay = @TAB & 'iTimeOut = iTimeOut + 1' & @CRLF _ & @TAB & 'If iTimeOut > ' & $iDelay & ' Then' & @CRLF _ & @TAB & @TAB & 'For Each oProcess in oWMIQuery' & @CRLF _ & @TAB & @TAB & @TAB & 'oProcess.Terminate()' & @CRLF _ & @TAB & @TAB & 'Next' & @CRLF _ & @TAB & @TAB & 'iExit = 2' & @CRLF _ & @TAB & 'End If' & @CRLF EndIf Local $sRemoveDir = '' If $fRemoveDir Then $sRemoveDir = 'oFileSystem.DeleteFolder "' & @ScriptDir & '", True' & @CRLF EndIf Local $sAppID = @ScriptName, $sImageName = 'Name' If $fUsePID Then $sAppID = @AutoItPID $sImageName = 'ProcessId' EndIf Local Const $iInternalDelay = 10, _ $sScriptPath = @ScriptFullPath Local Const $sData = 'Option Explicit' & @CRLF _ & 'Dim iExit, iTimeOut, oFileSystem, oProcess, oWMIQuery, oWMIService, sComputer, sFilePath, sWMIQuery' & @CRLF _ & @CRLF _ & 'sFilePath = "' & $sScriptPath & '"' & @CRLF _ & @CRLF _ & 'iExit = 0' & @CRLF _ & 'iTimeOut = 0' & @CRLF _ & 'sComputer = "."' & @CRLF _ & @CRLF _ & 'Set oWMIService = GetObject("winmgmts:" _' & @CRLF _ & @TAB & @TAB & '& "{impersonationLevel=impersonate}!\\" _' & @CRLF _ & @TAB & @TAB & '& sComputer & "\root\cimv2")' & @CRLF _ & @CRLF _ & 'sWMIQuery = "Select * From Win32_Process Where ' & $sImageName & ' = ''' & $sAppID & '''"' & @CRLF _ & @CRLF _ & 'While (iExit = 0)' & @CRLF _ & @TAB & 'Set oWMIQuery = oWMIService.ExecQuery(sWMIQuery)' & @CRLF _ & @TAB & 'If oWMIQuery.Count = 0 Then' & @CRLF _ & @TAB & @TAB & 'iExit = 1' & @CRLF _ & @TAB & 'End If' & @CRLF _ & @TAB & 'WScript.Sleep(1000)' & @CRLF _ & $sDelay _ & 'Wend' & @CRLF _ & @CRLF _ & 'WScript.Sleep(1000)' & @CRLF _ & 'iExit = 0' & @CRLF _ & 'iTimeOut = 0' & @CRLF _ & 'Set oFileSystem = CreateObject("Scripting.FileSystemObject")' & @CRLF _ & 'While (iExit = 0)' & @CRLF _ & @TAB & 'iTimeOut = iTimeOut + 1' & @CRLF _ & @TAB & 'If oFileSystem.FileExists(sFilePath) Then' & @CRLF _ & @TAB & @TAB & 'oFileSystem.DeleteFile sFilePath, True' & @CRLF _ & @TAB & 'End If' & @CRLF _ & @TAB & 'If oFileSystem.FileExists(sFilePath) <> True Then' & @CRLF _ & @TAB & @TAB & 'iExit = 1' & @CRLF _ & @TAB & 'End If' & @CRLF _ & @TAB & 'If iTimeOut > ' & $iInternalDelay & ' Then' & @CRLF _ & @TAB & @TAB & 'iExit = 2' & @CRLF _ & @TAB & 'End If' & @CRLF _ & 'Wend' & @CRLF _ & @CRLF _ & $sRemoveDir _ & 'oFileSystem.DeleteFile WScript.ScriptFullName, True' & @CRLF _ Local Const $hFileOpen = FileOpen($sTempFileName, $FO_OVERWRITE) If $hFileOpen = -1 Then Return SetError(2, 0, False) EndIf FileWrite($hFileOpen, $sData) FileClose($hFileOpen) Return ShellExecute($sTempFileName, @TempDir, @TempDir, '', @SW_HIDE) EndFunc ;==>_SelfDeleteExample use of Function:
#include <MsgBoxConstants.au3> #include '_SelfDelete.au3' _SelfDelete(30, 0) ; Start the SelfDelete batch file with a 30 second timer and using the prcocess name rather than the PID. If @error Then Exit MsgBox($MB_SYSTEMMODAL, '_SelfDelete()', 'The script must be a compiled exe to work correctly.') ; Display a warning if the script isn't compiled. EndIf While 1 Sleep(100) ; Wait or manually close the application via the traymenu icon. WEndWARNING: This will delete your executable if the function is called, so take the proper precautions and make sure you backup. -
masvil reacted to RTFC in Digital Display (numeric readout)
While developing a data visualisation tool I stumbled across >this awesome script by timmy2 and GDI grandwizard UEZ, and although I'm totally crap at graphics (craphics?), I had a stab at adapting it for more general use, incorporating some additional enhancements developed by more able graphics coders such as Beege, MrCreatoR and Malkey (acknowledgements and references to their relevant forum contributions are detailed in the script). Many thanks to you all! The result looks something like this:
So just to be absolutely clear: this is not my work, and I do not claim it to be my work. I've only repackaged it so you can easily create and maintain colourful displays like this with a few simple wrapper calls (see the example in the zip). Basically you create it once like a regular control (parse GUI handle, coordinates, size, and number of digits); that call then returns a display ID (1, 2, 3...). At this point the graphic is not yet visible. Internally, I've created specs storage for up to 100 displays; if you need more, just enlarge the array $DigiDispSpecs in the globals region.
Subsequently, once the GUI is itself visible, you can repeatedly update the displayed value (just make sure the value fits within the maximum number of digits specified when you created it; if parsing a value with fewer digits, these will be zero-padded). You can also change foreground colour, background colour, glow colour, and the intensity of that glow (range: 1-10; default 0 = off). You parse colour parameters either with colour strings ("red", "blue", "cyan", etc., easily expanded) or with their 6-digit hex RGB value (0xff0000 for red, for example). Remove individual readouts again by calling _DigitalDisplay_Remove($displayID). When you have removed the last digital display, you should call _DigitalDisplay_CleanUp() to avoid memory leaks. That's all, folks!
DigitalDisplay.7z beta version 0.9.
If it works, thank UEZ, timmy2, Beege, MrCreatoR and Malkey; if if breaks, blame me.
Hope you enjoy using it as much as I did cobbling it together!
RT
-
masvil reacted to RTFC in CodeCrypter - Encrypt your Script
CodeCrypter enables you to encrypt scripts without placing the key inside the script.
This is because this key is extracted from the user environment at runtime by, for example:
password user query any macro (e.g., @username) any AutoIt function call any UDF call some permanent environment variable on a specific machine (and not created by your script) a server response a device response anything else you can think of, as long as it's not stored in the script any combination of the above You need several scripts to get this to work, and they are scattered over several threads, so here's a single bundle that contains them all (including a patched version of Ward's AES.au3; with many thanks to Ward for allowing me to include this script here):
Latest version: 3.4 (3 Dec 2021): please follow this link.
Note: if you experience issues under Win8/8.1 (as some users have reported), please upgrade to Win10 (or use Win7) if you can; as far as I can tell, the scripts in the bundle all work under Win7 & Win10 (and XP). Moreover, I have no access to a Win8 box, so these issues will not be fixed, at least not by yours truly.
How the bits and pieces fit together:
CodeCrypter is a front-end for the MCF UDF library (you need version 1.3 or later). Its thread is here:
'?do=embed' frameborder='0' data-embedContent>>
The MCF package (also contained in the CodeScannerCrypter bundle) contains MCF.au3 (the library itself) plus a little include file called MCFinclude.au3. The latter you have to include in any script you wish to encrypt. Any code preceding it will not be encrypted, any code following it will be encrypted. You define the dynamic key inside MCFinclude.au3, in the UDF: _MCFCC_Init().
From the same post you can download an MCF Tutorial which I heartily recommend, because encrypting a script requires a number of steps in the right order, namely:
In MCFinclude.au3, define and/or choose your dynamic key(s) (skip this step = use default setting) include MCFinclude.au3 in your target script Run CodeScanner (version 2.3+) on your target script, with setting WriteMetaCode=True (see '?do=embed' frameborder='0' data-embedContent>>), then close CodeScanner. Start CodeCrypter press the Source button to load your target file enable Write MCF0 (tick the first option in Main Settings) Enable "Encrypt" (last option in the Main Settings) Go to the Tab Encrypt and set up the encryption the way you want (skip this = use default settings) Return to Main Tab and press "Run" if all goes well, a new script called MCF0test.au3 is created in the same directory as your target. It has no includes and no redundant parts. Please check that it works as normal. (see Remarks if not) It all sounds far more complicated than it is, really.
Not convinced? Check out:
a simple HowTo Guide: HowToCodeCrypt.pdf an updated and extended Q & A pdf (FAQ, also included in the bundle) to help you get started:CodeCrypterFAQ.pdf For additional explanations/examples in response to specific questions by forum members (how it works, what it can/cannot do), see elsewhere in this thread, notably:
Simple analogy of how it works: post #53, second part General Explanation and HowTo: post #9, 51, 75, 185/187, 196, 207, 270, 280 (this gets a bit repetitive) BackTranslation: post #179 Obfuscation: post #36 (general), 49 (selective obfuscation) Specific features and fixes: post #3 (security), 84 (redefining the expected runtime response), 169 (Curl Enum fix), 185/187 (using license keys), 194 (replacing Ward's AES UDF with different encryption/decryption calls), 251 (AV detection issue), 262 (extract key contents to USB on different target machine prior to encryption) Limitations: post #26 (@error/@extended), 149 (FileInstall), 191 (AES.au3 on x64) Not recommended: post #46/249 (static encryption), 102 (programme logic error), 237 (parsing password via cmdline)
Technical notes:
BackTranslation is a test to check that the MetaCode translation worked. Skip it at your peril. It also turns your multi-include composite script into a single portable file without redundant parts (you can opt to leave the redundant parts in, if you want).
CodeCrypter can also obfuscate (vars and UDF names) and replace strings, variable names and UDF names with anything else you provide, for example, for language translation). After CodeScanner separates your target's structure from its contents, CodeCrypter (actually MCF, under the hood) can change any part, and then generate a new script from whichever pieces you define. See the MCF Tutorial for more explanation and examples.
Encryption currently relies on Ward's excellent AES UDF and TheXman's sophisticated CryptoNG bundle. You can replace these with any other algorithm you like (but this is not trivial to do: edit MCFinclude.au3 UDF _MCFCC(), and MCF.au3 UDF _EncryptEntry(), see post #194 in this thread). AES by Ward, and CryptoNG by TheXman are also included in the bundle (with many thanks to Ward and TheXman for graciously allowing me to republish their outstanding work).
Going to lie down now...
RT
-
masvil reacted to RTFC in CodeCrypter - Encrypt your Script
Sure, just write a little function or direct call that does this (e.g., FileRead(" %TEMP%\password-inside.txt")) and stick this into the CCkey definition (in MCFinclude.au3) for the desired keyID. However, storing a password on file is a terrible, terrible idea.
-
masvil reacted to Ascend4nt in _FileFindEx - Get More from File/Folder Searches
_FileFindEx
Get More from File/Folder Searches
(formerly _WinAPI_FileFind)
Since it's always bugged me that the AutoIT implementation of 'FindFirstFile' and 'FindNextFile' only returned filenames and that extra calls had to be made to get file-size, attributes, short-names, and date/time of file creation,last-access, & last-modification which severely increased the amount of time it took to properly analyze the contents of a folder and it's files, I decided to create an alternative.
This uses the same Windows calls as AutoIT, except it returns all the information that it rightfully should for each file found - including:
File attributes (in numerical form, not a silly string format) Creation Time Last-Access Time Last-Write Time FileSize Filename (obviously) 8.3 short name (if it is 1. different from the regular Filename and 2. if short-names haven't been turned off Reparse Point info (if available) Now, the calling process is a little different, though for the most part not much is required to be altered in existing code. Basically, the attributes-check for folders is a numerical test, and when a folder is found, you *need* to test for '.' and '..' navigation (fake) folders. Also, the 'While' loop changes into a 'Do-Until' loop. Additionally, the first _FileFindExFirstFile() call returns a file, whereas FileFindFirstFile() doesn't (which never made sense to me).
To convert times into a readable format, you'll need to pass the array to the _FileFindExTimeConvert() function. Optionally, you can get the _WinTimeFunctions UDF and call those functions using array index constants:
$FFX_CREATION_TIME, $FFX_LAST_ACCESS_TIME, or $FFX_LAST_MODIFIED_TIME.
Note all _FileFindEx* calls are done using a special array, though 'ByRef' for quicker performance.
A nice application I found for this UDF was comparing files/folders - which is pretty easy using 64-bit filetime and file-size comparisons (no need for time conversion there).
The ZIP includes 4 files: the _FileFindEx UDF, FileFindExTest, the license agreement (same as below), and _LinkedOutputDisplay. Please note that _LinkedOutputDisplay on its own is a mess - but its included as-is to help see a side-by-side comparison of the output from FileFindExTest.
To get all the same information that _FileFindEx provides, the AutoIt functions below would need to be called:
FileFindFirst/NextFile FileGetAttrib *** NOTE: This Fails to report on some attributes (Reparse Points, Sparse Files) *** FileGetTime *3 (one for each time - Creation, Last-Access, Last-Modified) FileGetSize FileGetShortName (note: this provides a full path, rather than just a file name) Please note that for a fair time comparison, a clean boot is needed for each test due to O/S buffering after a scan. Between boots, the order of function calls in 'FileFindExTest' would need to be swapped. In first-run tests, _FileFindEx has consistently been quicker when gathering more than basic filename info. However, running the UDF in 64-bit mode on Vista+ O/S's results in slower performance, hence this note:
*IMPORTANT* - Speed is severely affected on certain processors when the script is run in x64 mode. I therefore recommend running/compiling the code in both bit-modes beforehand to see what the speed difference is. On my machine I've found x86 is much faster, whereas x64 is much slower than AutoIt's search functions. Other's have so I'm guessing it must be how optimized the hardware architecture is at running x64 code.
Update Log:
Download the ZIP Here
Ascend4nt's AutoIT Code License agreement:
While I provide this source code freely, if you do use the code in your projects, all I ask is that:
If you provide source, keep the header as I have put it, OR, if you expand it, then at least acknowledge me as the original author, and any other authors I credit If the program is released, acknowledge me in your credits (it doesn't have to state which functions came from me, though again if the source is provided - see #1) The source on it's own (as opposed to part of a project) can not be posted unless a link to the page(s) where the code were retrieved from is provided and a message stating that the latest updates will be available on the page(s) linked to. Pieces of the code can however be discussed on the threads where Ascend4nt has posted the code without worrying about further linking. -
masvil reacted to mLipok in Smtp Mailer That Supports Html And Attachments.
$Body = "one" & @CRLF & "two" & @CRLF & "three" ..... ..... $Body = StringReplace($Body,@CRLF,'<br>') ;~ And now you can send your body message....
-
masvil reacted to maniootek in Smtp Mailer That Supports Html And Attachments.
Body is HTML language, use "<br>" instead of "@CRLF"