Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 03/01/2022 in all areas

  1. An easter egg type thing I made for a program that is based on other snow animation scripts I found on these forums that I thought I would share here in case anyone found it interesting. It is just moving around a bunch of label controls on top of everything else without interfering with usage of other controls. #NoTrayIcon #include <GUIConstants.au3> Global $runTimer = TimerInit() Const $GUIWIDTH = 500, $GUIHEIGHT = 200 $hGui = GUICreate("TEST", $GUIWIDTH, $GUIHEIGHT, -1, -1, -1, BitOR($WS_EX_LAYERED, $WS_EX_COMPOSITED)) $aSnow = snowInit() $hbut = GUICtrlCreateButton('test', 100,20,50,30) GUICtrlCreateEdit('test', 100,100,200,50) GUICtrlCreateGroup("Group 1", 350, 40, 90, 140) GUICtrlCreateRadio("Radio 1", 370, 80, 60, 15) GUICtrlCreateRadio("Radio 2", 370, 120, 60, 15) GUICtrlCreateGroup("", -99, -99, 1, 1) ;close group GUISetState(@SW_SHOW, $hGui) AdlibRegister(snowAnimate, 40) While True Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $hbut ConsoleWrite('button' & @CRLF) EndSwitch WEnd Func snowInit() Local Const $isnowflakes = 50 ; number of snowflakes Local $aSnow[$isnowflakes][5] ; 0=length/width, 1=left (x pos), 2=top (y pos), 3=handle, 4=fall speed ; create snowflakes For $i = 0 To UBound($aSnow) - 1 $aSnow[$i][3] = GUICtrlCreateLabel("*", 0, 0, 0, 0) GUICtrlSetState(-1, $GUI_DISABLE + $GUI_HIDE) ; $GUI_DISABLE allows click thru snow but changes to grey color, $GUI_HIDE so we can show it later GUICtrlSetStyle(-1, 0) ; removes grey color but still disabled, and prevent double-clicking copying text to clipboard GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT) ; for transparent label control over non-transparent window GUICtrlSetColor(-1, 0) ; snow color Next Return $aSnow EndFunc Func snowAnimate() Local Const $iMinR = 5 ; minimum length of the snowflake's side Local Const $iMaxR = 15; max length Local Const $creation_interval = 500 ; spawn new snowflake every X ms Local Static $lastCreationTime = 0 Local $now = TimerDiff($runTimer) For $i = 0 To UBound($aSnow) - 1 ; if this snowflake not visible yet If BitAND(GUICtrlGetState($aSnow[$i][3]), $GUI_HIDE) And ($now - $lastCreationTime > $creation_interval) Then snowRandomize($aSnow, $i, $iMinR, $iMaxR) GUICtrlSetState($aSnow[$i][3], $GUI_SHOW) $lastCreationTime = $now Else $aSnow[$i][2] += $aSnow[$i][4] ; increment y pos If Random(1,20,1) = 20 Then $aSnow[$i][1] += Random(-2, 2, 0) ; x randomness GUICtrlSetPos($aSnow[$i][3], $aSnow[$i][1], $aSnow[$i][2]) ; when it gets to bottom of screen, change to random size and x pos and move to top of screen again If $aSnow[$i][2] > $GUIHEIGHT Then snowRandomize($aSnow, $i, $iMinR, $iMaxR) EndIf EndIf Next EndFunc Func snowRandomize(ByRef $aSnow, $i, $iMinR, $iMaxR) $aSnow[$i][0] = Random($iMinR, $iMaxR, 0) ; dimension of snow $aSnow[$i][1] = Random(0 - $iMaxR, $GUIWIDTH + $iMaxR, 0) ; x position $aSnow[$i][2] = 0 - $iMaxR ; y position (out of screen at startup) $aSnow[$i][4] = Random(0.05, 2) GUICtrlSetPos($aSnow[$i][3], $aSnow[$i][1], $aSnow[$i][2], $aSnow[$i][0], $aSnow[$i][0]) GUICtrlSetFont($aSnow[$i][3] , Floor(0.25 + $aSnow[$i][0]*1.25), 800, 0, '', 4) EndFunc ;==>_Randomize
    2 points
  2. I am sure you can answer that one yourself when you take 1 minute to look at those functions. ...and when it still isn't clear you can check au3.properties for the explanation:
    1 point
  3. I found another topic on this CDP protocol using pipes Automate Chrome / Edge using VBA - CodeProject
    1 point
  4. True. 2:58 AM here. πŸ€ͺ
    1 point
  5. You are correct that the size of a WLAN_BSS_ENTRY is 360 bytes. However, your parsing of the information is off for a couple of reasons: You are not properly taking into account the alignment bytes within the structure. There is a difference between BOOL and BOOLEAN. BOOL is 4 bytes and BOOLEAN is one. If you run the script below, it will display the structure (including the alignment bytes or padding as you call it). The displaying of the structure should help you correctly parse your data. Looking at the image you posted, I think my definition of the structures are correct. Of course if you use the _WinAPI_DisplayStruct() function in your script, with valid BSS ENTRY data , it should show you your correctly parsed data. #include <WinAPIDiag.au3> Global $gtag_DOT11_SSID = _ "struct;" & _ "ulong uSSIDLength;" & _ "byte ucSSID[32];" & _ "endstruct;" Global $gtag_WLAN_RATE_SET = _ "struct;" & _ "ulong uRateSetLength;" & _ "ushort usRateSet[126];" & _ "endstruct;" Global $gtag_WLAN_BSS_ENTRY = _ "struct;" & _ $gtag_DOT11_SSID & _ "ulong uPhyId;" & _ "byte dot11Bssid[6];" & _ "int dot11BssType;" & _ "int dot11BssPhyType;" & _ "long lRssi;" & _ "ulong uLinkQuality;" & _ "boolean bInRegDomain;" & _ "ushort usBeaconPeriod;" & _ "uint64 ullTimestamp;" & _ "uint64 ullHostTimestamp;" & _ "ushort usCapabilityInformation;" & _ "ulong ulChCenterFrequency;" & _ $gtag_WLAN_RATE_SET & _ "ulong ulIeOffset;" & _ "ulong ulIeSize;" & _ "endstruct;" ;Create an empty WLAN_BSS_ENTRY and display it Global $t_WLAN_BSS_ENTRY = DllStructCreate($gtag_WLAN_BSS_ENTRY) _WinAPI_DisplayStruct($t_WLAN_BSS_ENTRY, $gtag_WLAN_BSS_ENTRY, "WLAN_BSS_ENTRY") Partial Struct Display
    1 point
  6. Maybe this : #include <Excel.au3> #include <File.au3> Global $oExcel = _Excel_Open() Global $oWorkbook = _Excel_BookOpen($oExcel, @ScriptDir & "\Price.xlsx") If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error opening") Local $aExcel = _Excel_RangeRead($oWorkbook, Default, $oWorkbook.ActiveSheet.Usedrange.Columns("B:L")) $hRevdr1 = FileOpen(@ScriptDir & "\Revdr1.txt", $FO_OVERWRITE) $hRevdr2 = FileOpen(@ScriptDir & "\Revdr2.txt", $FO_OVERWRITE) $hRevdr3 = FileOpen(@ScriptDir & "\Revdr3.txt", $FO_OVERWRITE) $hCons1 = FileOpen(@ScriptDir & "\Cons1.txt", $FO_OVERWRITE) $hCons2 = FileOpen(@ScriptDir & "\Cons2.txt", $FO_OVERWRITE) $hCons3 = FileOpen(@ScriptDir & "\Cons3.txt", $FO_OVERWRITE) For $i = 0 To UBound($aExcel) - 1 If $aExcel[$i][8] = 0 Then If $aExcel[$i][4] = 2 Then FileWrite($hRevdr1, $aExcel[$i][0] & @CRLF) FileWrite($hRevdr2, $aExcel[$i][2] & @CRLF) FileWrite($hRevdr3, $aExcel[$i][10] & @CRLF) EndIf If $aExcel[$i][4] = 3 Then FileWrite($hCons1, $aExcel[$i][0] & @CRLF) FileWrite($hCons2, $aExcel[$i][2] & @CRLF) FileWrite($hCons3, $aExcel[$i][10] & @CRLF) EndIf EndIf Next FileClose($hRevdr1) FileClose($hRevdr2) FileClose($hRevdr3) FileClose($hCons1) FileClose($hCons2) FileClose($hCons3) It is taking less than 8 secs...But I didn't made much verification.
    1 point
  7. Hi folks, I finished the first design mockup for the answer tool, called Au3AnswerByTag. The backend code is still in progress, but I achieved the functional breakthrough 🀞 . I am already in contact with @barkeeper by private message, but I will you inform about the progress. In case your offer still exist, I will let you know when you can test the application @Nine πŸ˜€ . Image: Program opened Image: Answer displayed by chosen tag Best regards Sven ________________ Stay innovative!
    1 point
  8. A little primer on how I created a multilingual interface, for those who are interested. For starters, I prefer using arrays in order to manage my GUIs. It's so much easier to debug with _ArrayDisplay(). DacoDate mainly sets up six arrays: 1. One that contains all the translations ($aGUI_LANG), 2. The main program GUI ($aGUI_Main) 3. The "Memory" sub-menu ($aGUI_Memoire) 4. The "Option" sub-menu ($aGUI_Option) 5. The "A Propos" ($aGUI_APropos) 6. The "Progress" sub-menu ($aGUI_Progress) Array #1 ($aGUI_LANG) has two dimensions. The first is the line number to be translated, the second is the language in which this line is translated to. Essentially this is what it looks like: English French Italian ... [Hello] [Bonjour] [Buongiorno] ... [Bye] [Au revoir] [Arrivederci] ... ... ... ... The order of the languages is inspired by the excellent example from the AutoIt helpfile. Check out the appendix --> @OSLang Values Arrays #2-6 are simple arrays (from 0 to whatever) and host the return values for the creation of each GUI element I quickly ran into a feature I wanted to add: not only translate each line of text but ALSO translate each tooltip. There was two ways of going about this and I'll explain my choice Method 1 : add an extra dimension to the array --> $aGUI_Lang[Line][Language][Item] Method 2 : double the lines in the array: odd number = actual text, even number = tooltip I chose method 2 simply for the fact that displaying the content of a 3-dimension array isn't very convenient. So that basically means there's two lines per item, giving you the following result English French Italian ... [Hello] [Bonjour] [Buongiorno] ... [Click here] [Cliquez ici] [Clicca qui] ... [Bye] [Au revoir] [Arrivederci] ... [Don't click here] [Ne cliquez pas ici] [Non fare clic qui] ... ... ... ... In order to restore the values back to the GUI you'd do commands like these: $aGUIMain[0] = GUICreate($aGUI_Lang[0][n]) ; Create the main GUI, 'n' is replaced by the language / variable you want $aGUIMain[1] = GUICtrlCreateButton($aGUI_Lang[2][n],Top,Left) ; Next is a button. Notice how we skipped from [0] to [2] because the main GUI has no tooltip GUICtrlSetTip($aGUIMain[1], $aGUI_Lang[3][n]) ; Now we set the tip. Notice how [3] is an odd number. In my program I go about it programmatically by using for / next loops: For $i = 0 To UBound($aGUI_Main) - 1 ; Go through all values in the main GUI array         If $aGUI_Lang[$i * 2][$iLang] <> "" Then GUICtrlSetData($aGUI_Main[$i], $aGUI_Lang[$i * 2][$iLang]) ; If it isnt empty, set the value. $iLang is the language selected the user. Notice how $i is multiplied by two to factor in the text / tooltip design         If $aGUI_Lang[($i * 2) + 1][$iLang] <> "" Then GUICtrlSetTip($aGUI_Main[$i], $aGUI_Lang[($i * 2) + 1][$iLang]) ; Do the same with the tooltip. Notice how its all + 1     Next  This also applies to message boxes and different tools but the odd fields aren't used for tooltips: $sSelection = FileOpenDialog($aGUI_Lang[258][$iLang], $sDefaultFolder, $aGUI_Lang[259][$iLang], BitOR($FD_FILEMUSTEXIST, $FD_PATHMUSTEXIST)) ; First $aGUI_Lang[][] value is title of the window, then the folder where the file selector will start, then the second $aGUI_Lang[][] value represents the filter : "Log (*.log)" and finally the options (file and path must exist). Same with any MsgBox command where the odd field is the actual question while the even field is the window title. $iMsgBoxAnswer = MsgBox(292, $aGUI_Lang[242][$iLang], $aGUI_Lang[243][$iLang]) ; "Voulez vous exporter la liste?", "Voulez-vous exporter la liste de fichiers?" Notice how I commented the original text value. It can get complicated real quick so commenting your code is essential Some more program mechanics: Now the whole idea is a user can change the GUI language on-the-fly. There's two ways (I can see) of going about it: - Delete and re-creating the GUI each time - Refresh the parts of the GUI that can change In terms of refreshing speed the latter is obviously the best choice. So I've split the GUI creation into two parts: - _GUI_Main ; This part contains all the "Create" functions for ALL the GUIs, including sub-menus. We'll only run this ONCE. - _GUI_Peupler : This part "populates" all the GUIs, including GUICtrlSetData, GUICtrlSetTooltip, GUICtrlSetState and GUISetState So the logic behind this is if a user selects another language, we immediately call _GUI_Peupler() and Bob's your uncle. I've also streamlined the refresh as much as I could so that there is as little wait time as possible to get the GUI in the desired language. As an added bonus I also created an "emergency" button so that all values (including the language) are reset to their default values and the language is set once again to the OS's current language. Try Ctrl+Shift+Alt+'r'. Creating the translation file: Last part: how do you create a translation file and where do you put it? There's at least two ways to proceed here. The first one is quite cumbersome and implies creating the array inline. Setting the cells is a bit like this. It's a major chore: Global Const $aGUI_Lang[50][3] ; 50 lines, 3 languages $aGUI_Lang[0][0] = "Hello" $aGUI_Lang[0][1] = "Bonjour" $aGUI_Lang[0][2] = "Buongiorno" $aGUI_Lang[1][0] = "Click here" $aGUI_Lang[1][1] = "Cliquez ici" $aGUI_Lang[1][2] = "Clicca qui" ... The second way is much better (specially if you've got a ton of messages / languages to translate) but as a downside requires an external file. I've used LibreOffice's Calc since it's free. I guess you could also use Excel or Google Sheets. Whatever floats your boat. Calc is ideal to make a two-dimentionnal array. As per the included example, each row (two by two) is a GUI pair (text and tooltip) and each column is a different language. IMPORTANT: In order to export to a compatible file for this program you must do the following steps in Calc : File --> Create a copy --> Type, choose CSV --> type in "DacoDate.res" as filename --> when prompted for options, don't touch anything except making sure "Put values between quotes" is NOT checked. IMPORTANT: As a limitation, you must not use commas in any of your entries, since it will obviously bork the program. You could replace the commas by semicolons. Just make sure you tell _FileReadToArray() about it (see below). You'll notice in the joined .ODS file the last column has a "!" included in it. I found that if I didn't put something in the last field, Calc would simply export the first empty field and then go to the next line. That's why as soon as the ressource file is imported in AutoIt, I redim the last column out: $ierr = _FileReadToArray(@ScriptDir & "\" & "DacoDate.res", $aTempo, $FRTA_NOCOUNT, ",") ; Import resource file, put it in "$aTempo, don't use cell 0 to indicate count and automagically seperate fields using a comma ReDim $aTempo[UBound($aTempo)][UBound($aTempo, 2) - 1] ; Leave rows as they are. Remove last column A few downsides: In conclusion, there are a few downsides to using this approach to translate your program. Although for me the advantages far outweigh the drawbacks. 1. The code can get quite cryptic at times so you need to put whatever text value you expect in the comments. COMMENT, COMMENT, COMMENT! 2. You need to plan ahead. If you insert rows and columns too often you are just asking for trouble. If need be put empty rows / columns so you can add extra values later 3. Keep a list handy of what row says what. My file has grown from 20 to 260 ish lines and will probably grow by the time I'm finished. So that's it. Hopefully this will come in handy. And if someone knows a few languages in the list I'd appreciate a *proper* translation
    1 point
  9. Jon

    AutoIt v3.3.15.5 Beta

    5,158 downloads

    3.3.15.5 (27th February, 2022) (Beta) AutoIt: - Added #3826: GUI "On event" While loop precision. - Added: Doc Symbolic constants for MouseGetCursor(), GUISetCursor() $MCID_*. - Added #3849: @OSVersion for Windows 11 and Server 2022. - Fixed #3836: FileExits trailing quotation mark. - Fixed #3844: Right bracket does not register as a hotkey. - Fixed #3830: GUICtrlSetResizing $GUI_DOCKBOTTOM fullscreen. - Fixed #3831: GUICtrlSetPos $GUI_DOCKHCENTER. - Fixed #2696: StringRegExp non-participating groups. - Fixed #2866: Regread x64 remote from x86. - Fixed #3667: empty continuation line. - Fixed #3760: oversized Number conversion. - Fixed #3215: GUICtrlCreateUpdown Show-Hide. UDFs: - Added: $ARRAYDISPLAY_NUMERICSORT for selected column for _ArrayDisplay() and _DebugArrayDisplay(). - Added: _GUICtrlEdit_SetPadding(). - Added: _WinAPI_ShellExecuteEx() Doc example. - Fixed #3828: SetError(), SetExtended() broken doc links. - Fixed #3827: _GUICtrlListView_ClickItem() outside listview area. - Fixed #3835: Magic numbers in GDIPlus doc. - Fixed #3833: _WinAPI_RegisterRawInputDevices() $iCount. - Fixed #3842: -StringToArray() default parameter doc precision. - Fixed #3846: missing $LVKF_* constants definition. - Fixed #3847: _GUICtrlEdit_ShowBalloonTip() crash in _WinAPI_MultiByteToWideChar(). - Fixed #3848: _GUICtrlListView_GetItemTextArray() no error detection in multicolumn. - Fixed #3850: _WinAPI_GetDriveNumber() does return - 1 as partition number. - Fixed #3852: _ArrayToString() speed optimization. - Fixed: Constants for _WinAPI_GetCursorInfo(). - Fixed: Debug.au3 when stripping. - Fixed #3861: RunAs() doc remark.
    1 point
  10. 1 point
  11. Hi @Nine, πŸ‘ , glad to read that πŸ˜‚ . Actually it's quite simple, if it's feasable πŸ˜‰ . I will create a GUI, embedd an IE object, load a javascript RTF editor and interact with that editor by innerHTML object evaluation. I hope to store the format information of the editor in SQLite. I scroll through the tags and show the answer in the js RTF editor (hope so). That's it basically. Don't do this earlier πŸ˜… , I want to do the POC. Just kidding, do what ever you want. And to be honest, I am interested in your opinion about these thoughts. Best regards Sven ________________ Stay innovative!
    1 point
  12. Hi @barkeeper, I followed the thread (the conversation) here and found it would be helpful to contribute. I will also provide a little example like @Nine did πŸ‘ . My approach will contain a database usage because I have a similar requirement for another project (probably with more data). This means it could be useful for me too. I try to provide basic functionality to fit your mentioned requirements (as I understood them πŸ˜…). Afterwards I will restructure the project to to meet my requirements. My implementation will take a while. So if you can not wait (few days) go ahead and try to use and expand the nice example of @Nine. Yes the file approach should be easier. Regarding the possible multiple access handling, a database would do it on his own. That's why I would prefer that way πŸ˜€ . I hope I can bring a suggestion pretty soon, but don't count on it. Best regards Sven ________________ Stay innovative!
    1 point
  13. Hi folks, personally, I felt it always unclean or simply ugly to include whole UDFs into his script or project, in cases where you need only individual functions from it. The fact that the *.exe gets larger when compiling is often no longer a problem these days or you just don't mind it anymore - I, on the other hand, do somehow πŸ˜… . That's why I used to take the individual functions from the UDFs into my script so that I didn't have to include the entire UDF (#include). Depending on the license, I have recorded the attribution of the UDF creators or the contributors in the credits or similar to keep it fair. Then the change came: I got to know Visual Studio Code (VSCode) professionally, first for other languages, then also for AutoIt. With VSCode's rapidly improving and nowadays very powerful IntelliSense (code completion) I got an idea. Easy and fast: I store functions that I often need or have in some (own) UDFs in snippet files and can quickly insert them into the respective script or project if required. But it's important to me that I can access the functions contained in the snippets from anywhere - on my private computer, at work or at a colleague's/friend's. So I created a VSCode Extension πŸ˜€ . VSCode-AutoItSnippets: If you also implement your AutoIt projects with VSCode, then my AutoIt Snippets Extension might interest you or even help you to implement your projects faster. I would be very happy if you could take a look at the project. Of course, I'm interested in your opinion on this as well as whether one or the other would like to share their function(s) and would also like to have them immortalized in the extension 🧐 . If this should be interesting for you, then you are welcome to add your functions via pull request, or just write them here so I can include them in the snippet files, or you write with a private message or email. I'm curious if this can be helpful for you, because there are already over 500 installations of the extension, which makes me happy 😁 . This is how it looks in practice/in use: https://github.com/Sven-Seyfert/VSCode-AutoItSnippets#features Best regards Sven ________________ Stay innovative!
    1 point
  14. Hi folks, I released Version v2.1.0, see CHANGELOG. @big_daddy I changed to proper escape pattern βœ” I switched to !_ instead of !au3_, because almost all user defined functions starting with a underscore ⚠ Function names are adjusted to starting with capital letter (after the underscore) to fit more common practise βœ” I still try to provide a user friendly way of snippet generation (the snippet management extensions that you mentioned, aren't that good) ⚠ Next release coming soon 😁 . Best regards Sven ________________ Stay innovative!
    1 point
  15. JScript

    UDF: _HostFile.au3

    Hello all, This functions is used for manipulate Host file located in %Systemroot%\System32\Drivers\Etc\Host. Current functions: ; =============================================================================================================================== _HostRead( [FilePath] ) _HostReadLine( LineNumber [, FilePath ] ) _HostWrite( IP, HostName [, OverWrite [, FilePath ]]) _HostDelete( IP, HostName [, FilePath ]) ; ===============================================================================================================================Send comments... #include-once #include <Array.au3> ; #INDEX# ======================================================================================================================= ; Title .........: _HostFile.au3 ; AutoIt Version.: 3.2.12++ ; Language.......: English ; Description ...: Functions that manipulate Host file located in %Systemroot%\System32\Drivers\Etc\Host. ; Author ........: JoΓ£o Carlos (jscript) ; =============================================================================================================================== ; #CURRENT# ===================================================================================================================== ;_HostRead ;_HostReadLine ;_HostWrite ;_HostDelete ; =============================================================================================================================== ; #INTERNAL_USE_ONLY#============================================================================================================ ;============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name...........: _HostRead ; Description ...: Read all contents in the Host file. ; Syntax.........: _HostRead( [FilePath] ) ; Parameters ....: FilePath - [optional] The default location and name is %Systemroot%\System32\Drivers\Etc\Host. ; Return values .: Success - Sets @error = 0 and returns an two-dimensional array: ; $array[0][0] - Number of lines returned ; $array[1][0] - Line number ; $array[1][1] - IP number ; $array[1][2] - Host name ; ... ; $array[n][0] = nth Line number ; $array[n][1] = nth IP number ; $array[n][2] = nth Host name ; Failure - Returns the same two-dimensional array above with all values = 0 and: ; Sets @error = 1 if can not be open file ; Author ........: jscript (JoΓ£o Carlos) ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; $aHost = _HostRead() ; =============================================================================================================================== Func _HostRead($FilePath = "") Local $FileOpen, $aFileLines, $nCount, $Line = "", $RedirectIP[1][3] = [[0, 0, 0]] If $FilePath = "" Then $FilePath = @SystemDir & "\Drivers\Etc\hosts" ;Read the file into an array $FileOpen = FileOpen($FilePath, 0) If $FileOpen = -1 Then Return SetError(1, 0, $RedirectIP) Local $FileRead = FileRead($FileOpen, FileGetSize($FilePath)) & @LF $aFileLines = StringSplit(StringStripCR($FileRead), @LF) For $nCount = 1 To $aFileLines[0] $Line = StringStripWS($aFileLines[$nCount], 7) ; Skip comment lines proceeded by: # If StringLen($Line) < 10 Or StringRegExp(StringStripWS($Line, 8), "\A#") Then ContinueLoop ; $Line = StringSplit($Line, " " & Chr(9)) ;If @error Then $Line = StringSplit($Line, Chr(9)) If Not @error Then ReDim $RedirectIP[UBound($RedirectIP, 1) + 1][3] $RedirectIP[0][0] += 1 $RedirectIP[$RedirectIP[0][0]][0] = $nCount $RedirectIP[$RedirectIP[0][0]][1] = $Line[1] $RedirectIP[$RedirectIP[0][0]][2] = $Line[2] EndIf Next FileClose($FileOpen) Return $RedirectIP EndFunc ; #FUNCTION# ==================================================================================================================== ; Name...........: _HostReadLine ; Description ...: Read the specified line number in Host file. ; Syntax.........: _HostReadLine( LineNumber [, FilePath ] ) ; Parameters ....: LineNumber - Specified line number to be read. ; FilePath - [optional] The default location and name is %Systemroot%\System32\Drivers\Etc\Host. ; Return values .: Success - Sets @error = 0 and returns an one-dimensional with 2 elements: ; $array[0] - IP number ; $array[1] - Host name ; Failure - Sets @error = 1 and returns the same one-dimensional array above with 0 value. ; Author ........: jscript (JoΓ£o Carlos) ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; $aHost = _HostReadLine($array[1][0]) ; =============================================================================================================================== Func _HostReadLine($LineNumber, $FilePath = "") Local $FileOpen, $aFileLines, $nCount, $Line = "", $RedirectIP[2] = [0, 0] If $FilePath = "" Then $FilePath = @SystemDir & "\Drivers\Etc\hosts" ;Read the file into an array $FileOpen = FileOpen($FilePath, 0) If $FileOpen = -1 Then Return SetError(1, 0, $RedirectIP) Local $FileRead = FileRead($FileOpen, FileGetSize($FilePath)) & @LF $aFileLines = StringSplit(StringStripCR($FileRead), @LF) For $nCount = 1 To $aFileLines[0] $Line = StringStripWS($aFileLines[$nCount], 7) ; Skip comment lines proceeded by: # If StringLen($Line) < 10 Or StringRegExp(StringStripWS($Line, 8), "\A#") Then ContinueLoop $Line = StringSplit($Line, " ") If Not @error And $nCount = $LineNumber Then $RedirectIP[0] = $Line[1] $RedirectIP[1] = $Line[2] ExitLoop EndIf Next FileClose($FileOpen) Return $RedirectIP EndFunc ; #FUNCTION# ==================================================================================================================== ; Name...........: _HostWrite ; Description ...: Write redirections IP and HostName in the Host file. ; Syntax.........: _HostWrite( IP, HostName [, OverWrite [, FilePath ]]) ; Parameters ....: IP - IP addres. ; HostName - Host name. ; OvewrWrite - [optional] If set to 1, over write an existe value, the defaul is 0 ; FilePath - [optional] The default location and name is %Systemroot%\System32\Drivers\Etc\Host. ; Return values .: Success - Returns 1 ; Failure - Returns 0 and sets @error to: ; 1 - if file is readonly ; 2 - if file can not be open ; 3 - if not output file in write mode ; 4 - if file cannot be written ; Author ........: jscript (JoΓ£o Carlos) ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; _HostWrite($IP, $HostName, 1) ; =============================================================================================================================== Func _HostWrite($IP, $HostName, $OverWrite = 0, $FilePath = "") Local $FileOpen, $aFileLines, $hWriteHandle, $nCount, $Line = "", $Flag = True, $Value0, $Value1 If $FilePath = "" Then $FilePath = @SystemDir & "\Drivers\Etc\hosts" ; Check if file is readonly... If StringInstr(FileGetAttrib($FilePath), "R") Then Return SetError(1, 0, 0) ;Read the file into an array $FileOpen = FileOpen($FilePath, 0) If $FileOpen = -1 Then Return SetError(2, 0, 0) Local $FileRead = FileRead($FileOpen, FileGetSize($FilePath)) & @LF $aFileLines = StringSplit(StringStripCR($FileRead), @LF) ;Open the output file in write mode $hWriteHandle = FileOpen($FilePath, 2) If $hWriteHandle = -1 Then Return SetError(3, 0, 0) ;Loop through the array For $nCount = 1 To $aFileLines[0] $Line = StringStripWS($aFileLines[$nCount], 7) ; Skip comment lines proceeded by: # If StringLen($Line) < 10 Or StringRegExp(StringStripWS($Line, 8), "\A#") Then ContinueLoop $Value0 = StringRegExp($Line, "\b" & $IP & "\b") $Value1 = StringRegExp($Line, "\b" & $HostName & "\b") If ($Value0 And $Value1) Or ($OverWrite And ($Value0 Or $Value1)) Then $aFileLines[$nCount] = $IP & " " & $HostName $Flag = False ExitLoop EndIf Next If $Flag Then _ArrayInsert($aFileLines, $aFileLines[0], $IP & " " & $HostName) ;Write the lines back to original file. For $nCount = 1 To UBound($aFileLines) - 1 $Line = StringStripWS($aFileLines[$nCount], 7) If $Line = "" Then ContinueLoop ; If FileWriteLine($hWriteHandle, $aFileLines[$nCount]) = 0 Then FileClose($hWriteHandle) Return SetError(4, 0, 0) EndIf Next FileClose($hWriteHandle) Return SetError(0, 0, 1) EndFunc ; #FUNCTION# ==================================================================================================================== ; Name...........: _HostDelete ; Description ...: Delete entries in the Host file. ; Syntax.........: _HostDelete( IP, HostName [, FilePath ]) ; Parameters ....: IP - IP addres. ; HostName - Host name. ; FilePath - [optional] The default location and name is %Systemroot%\System32\Drivers\Etc\Host. ; Return values .: Success - Returns 1 ; Failure - Returns 0 and sets @error to: ; 1 - if file is readonly ; 2 - if file can not be open ; 3 - if not output file in write mode ; 4 - if file cannot be written ; Author ........: jscript (JoΓ£o Carlos) ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; _HostDelete($IP, $HostName, 1) ; =============================================================================================================================== Func _HostDelete($IP = "", $HostName = "", $FilePath = "") Local $FileOpen, $aFileLines, $hWriteHandle, $nCount, $Line = "", $Flag = True If $FilePath = "" Then $FilePath = @SystemDir & "\Drivers\Etc\hosts" ; Check if file is readonly... If StringInstr(FileGetAttrib($FilePath), "R") Then Return SetError(1, 0, 0) ;Read the file into an array $FileOpen = FileOpen($FilePath, 0) If $FileOpen = -1 Then Return SetError(2, 0, 0) Local $FileRead = FileRead($FileOpen, FileGetSize($FilePath)) & @LF If ($IP <> "" And Not StringInStr($FileRead, $IP)) Or ($HostName <> "" And Not StringInStr($FileRead, $HostName)) Then _ Return SetError(3, 0, 0) $aFileLines = StringSplit(StringStripCR($FileRead), @LF) ;Open the output file in write mode $hWriteHandle = FileOpen($FilePath, 2) If $hWriteHandle = -1 Then Return SetError(4, 0, 0) ;Write the lines back to original file. For $nCount = 1 To UBound($aFileLines) - 1 $Line = StringStripWS($aFileLines[$nCount], 7) If $Line = "" Then ContinueLoop If $IP = "" And StringRegExp($Line, "\b" & $HostName & "\b") Then ContinueLoop If StringRegExp($Line, "\b" & $IP & "\b") And $HostName = "" Then ContinueLoop If StringRegExp($Line, "\b" & $IP & "\b") And StringRegExp($Line, "\b" & $HostName & "\b") Then ContinueLoop ; If FileWriteLine($hWriteHandle, $aFileLines[$nCount]) = 0 Then FileClose($hWriteHandle) Return SetError(5, 0, 0) EndIf Next FileClose($hWriteHandle) Return SetError(0, 0, 1) EndFunc@shai, Thank you for having found a mistake! Regards, JoΓ£o Carlos.
    1 point
×
×
  • Create New...