Leaderboard
Popular Content
Showing content with the highest reputation on 12/18/2018 in all areas
-
Was revisiting an old script I made for work years ago; it performs a local system scan and produces an HTML report. the report was very basic and ugly...now it's less ugly, so I thought I'd share. It collects system info (i.e. manufacturer, model, serial, CPU, RAM, BIOS ver., etc.), network card info, a device list & installed software list. Requires DeviceAPI.au3 UDF by Weaponx #NoTrayIcon ;#RequireAdmin #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_UseX64=n #AutoIt3Wrapper_Res_Fileversion=0.2.2.0 ;#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker #AutoIt3Wrapper_Run_Obfuscator=y #Obfuscator_Parameters=/cs=0 /cn=0 /cf=0 /cv=0 /sf=1 /sv=1 #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #NoAutoIt3Execute Global $version = "0.2.2" #cs - Version History 0.2.2 Bug fix [*] Corrected _WriteArrayToLog() destination file for debug 0.2.1 Minor Updates [+] Added System Info Attributes (OS, OS Version, Organization and Registered Owner) 0.2.0 Misc Updates [+] HTML Report Format - Initial Bootstrap CSS support [*] Minor report changes [*] Changed log write logic 0.1.5 Minor Updates [+] Added Obfuscation to Reduce Script Size [+] Set FileVersion to Match Script Version [+] Disabled external AutoIt script/code execution. 0.1.4 Significant Updates / Script Cleanup [-] Removed Omitted code from version 0.1.3 [*] Code Cleanup [*] Optimized Network Info WMI Query [+] Added HTML Footer [*] Changed HTML Report Header and added timestamps [*] Changed Script name to SystemScan 0.1.3 Major Updates / Script Cleanup & HTML Report [-] Removed Omitted code from version 0.1.2 [+] Added HTML Report Functions [+] Added Data Array Sort [*] Omitted Software & Device Hash Checking and Scan Force and Scan Version Reg Key [*] Omitted Uninstall String 0.1.2 Minor Updates / Script Cleanup [*] Changed All Collection Functions to Output Data Arrays [+] Created Array to Log File Method [-] Removed TimeZone from System Info Collection [*] Omitted User Name from System Info Collection [*] Omitted GUID Generation [*] Changed Scan Force to not remove or check Software and Device Signatures [*] Misc Code Cleanup [*] Omitted Software install date conversions 0.1.1 Minor Updates / Script Cleanup 0.1 Alpha Build #ce #Region - Initialization ;#AutoIt3Wrapper_Change2CUI=Y #include <Array.au3> ;Include Native AutoIt Library for Array Functions #include <DeviceAPI.au3> ;By Weaponx - https://www.autoitscript.com/forum/topic/77731-device-management-api/ #include <Constants.au3> ;Include Native AutoIt Library for AutoIt Constants #include <Date.au3> ;Include Native AutoIt Library for Date/Time Functions #include <Misc.au3> ;Include Native AutoIt Library for Misc. Functions (_Singleton()) ;Initialize Global $exitTimer = 0, $host = @ComputerName, $debug = 0 ;Define Global Variables for Timer, Hostname & Debug Flags Global $destDir = @ScriptDir & "\" ;Define LogFile Destination If Not _Singleton("DomainScan") Then Exit ;Enforce Singleton Execution If Not FileExists($destDir) Then DirCreate($destDir) ;Create Destination Dir Local $log = $destdir & "\" & @ComputerName & ".htm" $log = FileOpen($log, 2) FileDelete($destDir & "DomainScanLog.txt") ;Remove Debug Logfile ;Parse Command-Line Arguments for Debug and ScanForce Options If $CMDLINE[0] Then If StringInStr($CMDLINERAW, "debug") Then $debug = 1 ;Unused Function with Example Usage ;If StringInstr($CMDLINERAW,"/fileinfolist") Then ;domainscan.exe /fileinfolist "C:\dir\file.txt" ;_FileInfoList($CMDLINE[$CMDLINE[0]]) ;EndIf EndIf ;==>Initialize #EndRegion - Initialization #Region - Main ;Establish Local WMI Connection $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc") $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") If Not IsObj($objWMIService) Then If $debug Then _DebugLog("Failed to Establish WMI Connection") _Exit() EndIf If $debug Then _DebugLog("Established WMI Connection") ;==>Establish WMI Connection ;Timeout Timer $exitTimer = TimerInit() AdlibRegister("_ExitTimer", 30000) OnAutoItExitRegister("_Exit") ;==>Timeout Timer ;Collect System Data _WriteHTMLReportHeader($destDir) _AddSystemInfo($host) _AddSystemNetworkInfo($host) _AddSystemDevices($host) _AddSystemInstalledSoft($host) _WriteHTMLReportFooter($destDir) _Exit() ;==>Collect System Data ;Save log to NAS ;==>Save log to NAS #EndRegion - Main #Region - User Defined Functions Func _AddSystemInfo($hostname) ;Collect System Information If $debug Then _DebugLog("Collecting System Information") ;Execute WMI Queries $colItems = $objWMIService.ExecQuery("SELECT Name FROM Win32_Processor") For $objItem In $colItems $CPU = StringLeft(StringStripWS($objItem.name, 7), 64) Next $colItems = $objWMIService.ExecQuery("SELECT SerialNumber, SMBIOSBIOSVersion, ReleaseDate FROM Win32_BIOS") For $objItem In $colItems $Serial = $objItem.SerialNumber $BIOSVer = $objItem.SMBIOSBIOSVersion $ManufactureDate = $objItem.ReleaseDate $RealDate = ObjCreate("WbemScripting.SWbemDateTime") $RealDate.value = $ManufactureDate $ManufactureDate = StringRegExpReplace($RealDate.GetVarDate, "(\d{4,4})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})", "$2\/$3\/$1 $4:$5") $RealDate = 0 Next $colItems = $objWMIService.ExecQuery("SELECT TotalPhysicalMemory, Manufacturer, Model, Domain, UserName FROM Win32_ComputerSystem") For $objItem In $colItems $RAM = Round($objItem.TotalPhysicalMemory / 1024 / 1024) $Manufacturer = $objItem.Manufacturer $Model = StringLeft(StringStripWS($objItem.Model, 2), 30) $Domain = StringLeft($objItem.Domain, StringInStr($objItem.Domain, ".") - 1) Next $colItems = $objWMIService.ExecQuery("SELECT Caption, Version, Organization, RegisteredUser, LastBootUpTime, CurrentTimeZone FROM Win32_OperatingSystem") For $objItem In $colItems $OS = $objItem.Caption $OSVersion = $objItem.Version $Organization = $objItem.Organization $RegisteredUser = $objItem.RegisteredUser $LastBootTime = $objItem.LastBootUpTime $RealDate = ObjCreate("WbemScripting.SWbemDateTime") $RealDate.value = $LastBootTime $LastBootTime = StringRegExpReplace($RealDate.GetVarDate, "(\d{4,4})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})", "$2\/$3\/$1 $4:$5") $RealDate = 0 Next $colItems = 0 ;Collect Local Administrator Members $localadmins = "" Dim $filter[1] = ["Groups"] $colGroups = ObjGet("WinNT://" & $hostname & "") $colGroups.Filter = $filter For $objGroup In $colGroups If $objGroup.Name = "Administrators" Then For $objUser In $objGroup.Members If $objUser.Name Then $localadmins &= $objUser.Name & "|" Next EndIf Next If StringRight($localadmins, 1) = "|" Then $localadmins = StringTrimRight($localadmins, 1) $localadmins = StringLeft($localadmins, 255) ;Create Data Array Dim $arrSysInfo[2][14] = [["OS", "OS Version", "Owner", "Organization", "Manufacturer", "Model", "Serial", "BIOS Version", "BIOS Date", "CPU", "RAM", "Domain", "Last Boot Time", "Local Admins"], _ [$OS, $OSVersion, $RegisteredUser, $Organization, $Manufacturer, $Model, $Serial, $BIOSVer, $ManufactureDate, $CPU, $RAM, $Domain, $LastBootTime, $localadmins]] ;Save Collected Info If $debug Then _WriteArrayToLog($arrSysInfo, $destDir, "SystemInfo.CSV") $arrSysInfo[1][13] = StringReplace($arrSysInfo[1][13], "|", "</br>") _WriteArrayToHTML(__ArrayTranspose($arrSysInfo), $destDir, "System Information") If $debug Then _DebugLog("System Information Collected") EndFunc ;==>_AddSystemInfo Func _AddSystemNetworkInfo($hostname) ;Collect System Network Information If $debug Then _DebugLog("Collecting System Network Information") ;Execute WMI Queries Dim $arrNetInfo[1][8] = [["Interface Name", "MAC", "IP", "Subnet", "Gateway", "DNS1", "DNS2", "WINS"]] Dim $netIdx = 1 $colItems = $objWMIService.ExecQuery("SELECT IPAddress, Description, MACAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder, WINSPrimaryServer FROM Win32_NetworkAdapterConfiguration Where IPEnabled = True") For $objItem In $colItems If $objItem.IPAddress(0) <> "0.0.0.0" Then $NIC = StringLeft($objItem.Description, 90) $MAC = $objItem.MACAddress $IP = $objItem.IPAddress(0) $Subnet = $objItem.IPSubnet(0) $Gateway = $objItem.DefaultIPGateway(0) $DNS1 = $objItem.DNSServerSearchOrder(0) $DNS2 = $objItem.DNSServerSearchOrder(1) $WINS = $objItem.WINSPrimaryServer(0) ReDim $arrNetInfo[$netIdx + 1][8] $arrNetInfo[$netIdx][0] = $NIC $arrNetInfo[$netIdx][1] = $MAC $arrNetInfo[$netIdx][2] = $IP $arrNetInfo[$netIdx][3] = $Subnet $arrNetInfo[$netIdx][4] = $Gateway $arrNetInfo[$netIdx][5] = $DNS1 $arrNetInfo[$netIdx][6] = $DNS2 $arrNetInfo[$netIdx][7] = $WINS $netIdx += 1 EndIf Next $colItems = 0 _ArraySort($arrNetInfo, 0, 1, UBound($arrNetInfo) - 1) ;Save Collected Data If $debug Then _WriteArrayToLog($arrNetInfo, $destDir, "NetworkInfo.CSV") _WriteArrayToHTML(__ArrayTranspose($arrNetInfo), $destDir, "Network Information") If $debug Then _DebugLog("System Network Information Collected") EndFunc ;==>_AddSystemNetworkInfo Func _AddSystemInstalledSoft($hostname) ;Collect Installed Software Listing If $debug Then _DebugLog("Collecting Installed Software") ;Populate Software Collection Array Dim $arrSoft[1][3] = [["Software Title", "Version", "Install Date"]] Dim $appIdx = 1 If @OSArch <> "X64" Then $y = 1 Else $y = 2 EndIf For $x = 1 To $y $keyIdx = 0 ;Index of Uninstall SubKeys If $x = 1 Then $regRoot = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ;Registry Tree for Uninstall Info Else $regRoot = "HKLM64\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ;Registry Tree for Uninstall Info EndIf While 1 $keyIdx += 1 ;Increment Index each loop $keyName = RegEnumKey($regRoot, $keyIdx) ;Query Registry Key at Index $keyIdx If @error Then ExitLoop ;If not end of registry tree Local $appName = StringLeft(StringStripWS(RegRead($regRoot & "\" & $keyName, "DisplayName"), 7), 80) ;Get Application Name If $appName Then Local $versionNum = RegRead($regRoot & "\" & $keyName, "DisplayVersion") ;Get Version Number Local $installdate = RegRead($regRoot & "\" & $keyName, "InstallDate") ;Get Install Date If Not $versionNum Then $versionNum = "" ReDim $arrSoft[$appIdx + 1][3] $arrSoft[$appIdx][0] = $appName $arrSoft[$appIdx][1] = $versionNum $arrSoft[$appIdx][2] = $installdate $appIdx += 1 EndIf WEnd Next _ArraySort($arrSoft, 0, 1, UBound($arrSoft) - 1) If $debug Then _DebugLog("Adding System Software") ;Save Collected Info If $debug Then _WriteArrayToLog($arrSoft, $destDir, "Software.CSV") _WriteArrayToHTML($arrSoft, $destDir, "Installed Software") EndFunc ;==>_AddSystemInstalledSoft Func _AddSystemDevices($hostname) ;Collect Installed System Devices If $debug Then _DebugLog("Collecting System Devices") ;Populate Installed System Devices Array Dim $arrHW[1][3] = [["Device Name", "Class", "Manufacturer"]] $devIDX = 1 _DeviceAPI_Open() _DeviceAPI_GetAllDevices() ;Build list of ALL device classes While _DeviceAPI_EnumDevices() ReDim $arrHW[$devIDX + 1][3] $arrHW[$devIDX][0] = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC) $arrHW[$devIDX][1] = _DeviceAPI_GetClassName(_DeviceAPI_GetDeviceRegistryProperty($SPDRP_CLASSGUID)) $arrHW[$devIDX][2] = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG) $devIDX += 1 WEnd _DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure _DeviceAPI_Close() _ArraySort($arrHW, 0, 1, UBound($arrHW) - 1) If $debug Then _DebugLog("Adding System Devices") ;Save Collected Info If $debug Then _WriteArrayToLog($arrHW, $destDir, "Devices.CSV") _WriteArrayToHTML($arrHW, $destDir, "System Devices") EndFunc ;==>_AddSystemDevices Func __ArrayTranspose(ByRef $arr) If Not IsArray($arr) Then Return SetError(1, 0, 0) If Not UBound($arr, 0) = 2 Then Return SetError(2, 0, 0) Dim $arrTrans[UBound($arr, 2)][UBound($arr, 1)] For $x = 0 To UBound($arrTrans, 2) - 1 For $y = 0 To UBound($arrTrans) - 1 $arrTrans[$y][$x] = $arr[$x][$y] Next Next Return $arrTrans EndFunc ;==>__ArrayTranspose Func _DebugLog($str) FileWriteLine($destDir & "DomainScanLog.txt", @HOUR & ":" & @MIN & ":" & @SEC & " - " & $str) EndFunc ;==>_DebugLog Func _Exit() $exitTimer = 0 $objWMI = 0 FileClose($log) Exit EndFunc ;==>_Exit Func _ExitTimer() $time = 1200000 If $debug Then _DebugLog("Timer Check: " & TimerDiff($exitTimer) & @TAB & $time) If TimerDiff($exitTimer) > $time Then Exit EndFunc ;==>_ExitTimer Func _Today() Return @YEAR & @MON & @MDAY EndFunc ;==>_Today Func _WriteArrayToHTML($arr, $dest, $title) $xDim = UBound($arr, 1) - 1 $yDim = UBound($arr, 2) - 1 FileWriteLine($log, "<div class=""container""><h3><a href='#" & StringReplace($title," ","_") & "' data-toggle='collapse'>" & $title & "</a></h3>") FileWriteLine($log, "<div id='" & StringReplace($title," ","_") & "' class='collapse'><table border='0'>") $varRowColor = 0 For $x = 0 To $xDim If $varRowColor = 0 Then $varRowColor = 1 $varRowColorValue = "#9BCDFF" Else $varRowColor = 0 $varRowColorValue = "#C4E1FF" EndIf FileWrite($log, "<tr bgcolor='" & $varRowColorValue & "'>") For $y = 0 To $yDim FileWrite($log, "<td>" & $arr[$x][$y] & "</td>") Next FileWrite($log, "</tr>" & @CRLF) Next FileWriteLine($log, "</table></div></div></br>") EndFunc ;==>_WriteArrayToHTML Func _WriteArrayToLog($arr, $dest, $filename) $xDim = UBound($arr, 1) - 1 $yDim = UBound($arr, 2) - 1 For $x = 0 To $xDim For $y = 0 To $yDim FileWrite($destdir & "\" & @ComputerName & "_" & $filename, '"' & $arr[$x][$y] & '"') If $y < $yDim Then FileWrite($destdir & "\" & @ComputerName & "_" & $filename, ",") Else FileWrite($destdir & "\" & @ComputerName & "_" & $filename, @CRLF) EndIf Next Next EndFunc ;==>_WriteArrayToLog Func _WriteHTMLReportHeader($dest) $title = @ComputerName & " System Scan" FileWriteLine($log, '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">') FileWriteLine($log, '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>') FileWriteLine($log, '<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>') FileWriteLine($log, '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>') FileWriteLine($log, "<title>" & $title & "</title>" & @CRLF & _ "<div class=""jumbotron jumbotron-fluid""><div class=""container""><center><h1>" & $title & "</h1></div></div>" & _ "<div class=""container"">Scan Initiated: " & @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & "</br></br></br></div>") EndFunc ;==>_WriteHTMLReportHeader Func _WriteHTMLReportFooter($dest) FileWriteLine($log, "</div></br><div class=""container"">Scan Complete: " & @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & "</div>") FileClose($log) ShellExecute($dest & "\" & @ComputerName & ".htm") EndFunc ;==>_WriteHTMLReportFooter Func MyErrFunc() If $oMyError.number = -2147352567 Then Return 0 If $debug Then _DebugLog("Intercepted a COM Error !" & @CRLF & @CRLF & "err.description is: " & @TAB & $oMyError.description) Local $err = $oMyError.number If $err = 0 Then $err = -1 $g_eventerror = $err ; to check for after this function returns EndFunc ;==>MyErrFunc #EndRegion - User Defined Functions #Region - Functions Not Implemented ;Func _AddFileInfo($hostname,$file) ; If Not FileExists($file) Then Return 0 ; $attribs = FileGetAttrib($file) ; $size = FileGetSize($file) ; $version = FileGetVersion($file) ; $modtime = FileGetTime($file,0,1) ; $cretime = FileGetTime($file,1,1) ; $acctime = FileGetTime($file,2,1) ;EndFunc ;Func _FileInfoList($filelist) ; If Not FileExists($filelist) Then Return 0 ; Dim $arrList ; _FileReadToArray($filelist,$arrList) ; For $x = 1 to $arrList[0] ; ;_AddFileInfo(@ComputerName,$arrList[$x]) ; Next ;EndFunc #EndRegion - Functions Not Implemented The script produces a report that looks like this.1 point
-
ControlSend BUG
MovieScreener2013 reacted to jdelaney for a topic
Send is one have the hackiest ways to automate something. how can you expect to automate something reliably if you can't verify your action was received (rhetorical). maybe your window was not ready to accept input, maybe your network went down temporarily, maybe a popup became active. there is too many what ifs in a windows environment to ever use ONLY *send reliably. this is not a bug, it's a flaw in your scripting1 point -
ControlSend BUG
MovieScreener2013 reacted to Jos for a topic
I am seriously wondering what you are expecting as reply to your posts as they don't contain any information what you are doing other than screwing a working script? When you want any serious assistance you open a new thread in the support forum providing enough details about what you are doing and where things go wrong. Jos1 point -
Timed Start Command
boat_58 reacted to ModemJunki for a topic
I also agree that Task Scheduler is the most reliable/best way to have a task start at the same time every day. But for the sake of my own education I had a look at the perfectly good date/time macros in AutoIT, just in case you want your script to hang around doing not much until a certain time has come (say, 13 minutes past 1 in the afternoon), this much is simple. Do If @HOUR & ":" & @MIN = "13:13" Then ConsoleWrite(@HOUR & ":" & @MIN & @CRLF) ; write to console but could be any action really ExitLoop ; if we exit the loop it only runs once, remove if you want this to happen every day EndIf Sleep(1000) Until 0 But what if the time you specified in your code has already passed (such as the system was asleep)? Ok, just change the comparison operator so instead of "=" you use ">=", then it will trigger after the time has passed too. Really have a close look at Windows task scheduler (I'm looking at Windows 10) - you can set multiple triggers, you can define different conditions, you can define retry on failure (now, that looks interesting: how does the task schedule know a task has failed? What do we need in our script to assure this is properly working?), there is an history kept, etc.. The built-in scheduler is really pretty fail-safe once you have your task set up. Anyway someone tackled running tasks at set times a long time ago and there are good (simple) examples of using the Time and Date macros there, have a look, and best of luck!1 point -
Block Unblock Comm Ports
toasterking reacted to ViciousXUSMC for a topic
I was working on a little project to assign Com Ports for a USB GPS Device, one of the things I needed to do was unblock the old Com Port and Block the new one. When I say "Block" it reserves the port in the registry in a Key called ComDB under HKLM\SYSTEM\CurrentControlSet\Control\COM Name Arbiter How it does so is kind of complex because its basically Hex values in the registry representing Binary values for the Com Ports. I wanted a way to make changes to this Key without damaging the integrity of it (meaning preserve all settings that are current but make the needed changes) so I came up with these two functions. I have not done clean up on the code so I would not call it a UDF and just a full blown example. Here is the code: #Include <Array.au3> $vTest = _BlockComPort(25) MsgBox(0, "" , $vTest & " " & @Error & " " & @Extended) $vTest2 = _UnblockComPort(25) MsgBox(0, "" , $vTest & " " & @Error & " " & @Extended) ;Function _BlockComPort($iPortNumber) ;Return 1 if Succsess or already blocked, Return 0 if @Error, @Error 1 = Registry Issue @Extended 1 = Can Not Read Registry @Extended 2 = Can Not Write Registry Func _BlockComPort($iPortToChange) $sComDB = RegRead("HKLM\SYSTEM\CurrentControlSet\Control\COM Name Arbiter", "ComDB") If @Error Then SetError(1, 1, 0) Return EndIf $sComDB = StringTrimLeft($sComDB, 2) $aComDB = _StringChop($sComDB, 2) ;Array of ComDB ; _ArrayDisplay($aComDB) ;Debug Show Array $sArraySection =Ceiling($iPortToChange / 8) ;Returns the Array Row This Com Port Falls Into ConsoleWrite(@CRLF & "Array Section (Octect Count) " & $sArraySection) ;Debug Show Octect Count for Com Port $iHexValueOctet = $aComDB[$sArraySection] ConsoleWrite(@CRLF & "Current Com Port Octect Hex Value " & $iHexValueOctet) ;Debug Show Hex Value of Octet $iDecValueOctet = Dec($iHexValueOctet) ConsoleWrite (@CRLF & "Current Com Port Octect Decimal Value " & $iDecValueOctet) ;Debug Show Decimal Value of Octet $iBinaryValueOctet = _HexToBinaryString($iHexValueOctet) ConsoleWrite(@CRLF & "Current Com Port Octect Binary Value " & $iBinaryValueOctet) ;Debug Show Binary String of Octet Local $aPortValue[257][4] Local $iBitPlace = 9 ;_ArrayDisplay($aPortValue) ;Debug Show Array For $i = 1 to 256 $iBitPlace = $iBitPlace-1 $aPortValue[$i][0] = "COM" & $i $aPortValue[$i][1] = $iBitPlace If $iBitPlace = 1 Then $iBitPlace = 9 Switch $aPortValue[$i][1] Case 1 $aPortValue[$i][2] = 128 Case 2 $aPortValue[$i][2] = 64 Case 3 $aPortValue[$i][2] = 32 Case 4 $aPortValue[$i][2] = 16 Case 5 $aPortValue[$i][2] = 8 Case 6 $aPortValue[$i][2] = 4 Case 7 $aPortValue[$i][2] = 2 Case 8 $aPortValue[$i][2] = 1 EndSwitch $aPortValue[$i][3] = Ceiling($i/8) Next $aPortValue[0][0] = "COM Name" $aPortValue[0][1] = "Reverse Bit Place" $aPortValue[0][2] = "Decimal Value" $aPortValue[0][3] = "Octect Count" ;_ArrayDisplay($aPortValue) ;Debug Show Binary Table $iBinaryPosition = $aPortValue[$iPortToChange][1] ConsoleWrite(@CRLF & "Binary Position To Check for 1 (Blocked) or 0 (Unblocked) " & $iBinaryPosition) ;Debug Show What Postion is being checked and value ;Test of Blocked $vReturnTest = StringMid($iBinaryValueOctet, $iBinaryPosition, 1) ConsoleWrite(@CRLF & "Current Binary Value of Com Port " & $vReturnTest) ;Debug Shows Binary Value of This Com Port and If Blocked If $vReturnTest = 1 Then Return 1 ;Port already blocked exit function ;Find Decimal Value of Port $iDecToAdd = $aPortValue[$iPortToChange][2] $iNewDecTotal = $iDecToAdd + $iDecValueOctet ConsoleWrite(@CRLF & "New Decimal Value for Com Port Octet " & $iNewDecTotal) ;Debug Show New Decimal Value ;Convert Decimal To Hex $sNewHexTotal = Hex($iNewDecTotal, 2) ConsoleWrite(@CRLF & "New Hex Value for Com Port Octet " & $sNewHexTotal) ;Debug Show New Hex Value ;Make Changes to ComDB $aComDB[$sArraySection] = $sNewHexTotal ;_ArrayDisplay($aComDB) ;Debug Show New Array of ComDB Local $sNewReg For $i = 1 to $aComDB[0] $sNewReg &= $aComDB[$i] Next RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\COM Name Arbiter", "ComDB", "REG_BINARY", Binary("0x" & $sNewReg)) If @Error Then SetError(1, 2, 0) Return EndIf Return 1 ;Return 1 if No Errors EndFunc ;End BlockComPort Func _UnblockComPort($iPortToChange) $sComDB = RegRead("HKLM\SYSTEM\CurrentControlSet\Control\COM Name Arbiter", "ComDB") If @Error Then SetError(1, 1, 0) Return EndIf $sComDB = StringTrimLeft($sComDB, 2) $aComDB = _StringChop($sComDB, 2) ;Array of ComDB ; _ArrayDisplay($aComDB) ;Debug Show Array $sArraySection =Ceiling($iPortToChange / 8) ;Returns the Array Row This Com Port Falls Into ConsoleWrite(@CRLF & "Array Section (Octect Count) " & $sArraySection) ;Debug Show Octect Count for Com Port $iHexValueOctet = $aComDB[$sArraySection] ConsoleWrite(@CRLF & "Current Com Port Octect Hex Value " & $iHexValueOctet) ;Debug Show Hex Value of Octet $iDecValueOctet = Dec($iHexValueOctet) ConsoleWrite (@CRLF & "Current Com Port Octect Decimal Value " & $iDecValueOctet) ;Debug Show Decimal Value of Octet $iBinaryValueOctet = _HexToBinaryString($iHexValueOctet) ConsoleWrite(@CRLF & "Current Com Port Octect Binary Value " & $iBinaryValueOctet) ;Debug Show Binary String of Octet Local $aPortValue[257][4] Local $iBitPlace = 9 ;_ArrayDisplay($aPortValue) For $i = 1 to 256 $iBitPlace = $iBitPlace-1 $aPortValue[$i][0] = "COM" & $i $aPortValue[$i][1] = $iBitPlace If $iBitPlace = 1 Then $iBitPlace = 9 Switch $aPortValue[$i][1] Case 1 $aPortValue[$i][2] = 128 Case 2 $aPortValue[$i][2] = 64 Case 3 $aPortValue[$i][2] = 32 Case 4 $aPortValue[$i][2] = 16 Case 5 $aPortValue[$i][2] = 8 Case 6 $aPortValue[$i][2] = 4 Case 7 $aPortValue[$i][2] = 2 Case 8 $aPortValue[$i][2] = 1 EndSwitch $aPortValue[$i][3] = Ceiling($i/8) Next $aPortValue[0][0] = "COM Name" $aPortValue[0][1] = "Reverse Bit Place" $aPortValue[0][2] = "Decimal Value" $aPortValue[0][3] = "Octect Count" ;_ArrayDisplay($aPortValue) ;Debug Show Binary Table $iBinaryPosition = $aPortValue[$iPortToChange][1] ConsoleWrite(@CRLF & "Binary Position To Check for 1 (Blocked) or 0 (Unblocked) " & $iBinaryPosition) ;Debug Show What Postion is being checked and value ;Test of Blocked $vReturnTest = StringMid($iBinaryValueOctet, $iBinaryPosition, 1) ConsoleWrite(@CRLF & "Current Binary Value of Com Port " & $vReturnTest) ;Debug Shows Binary Value of This Com Port and If Blocked If $vReturnTest = 0 Then Return 1 ;Port already unblocked exit function ;Find Decimal Value of Port $iDecToAdd = $aPortValue[$iPortToChange][2] $iNewDecTotal = $iDecValueOctet - $iDecToAdd ConsoleWrite(@CRLF & "New Decimal Value for Com Port Octet " & $iNewDecTotal) ;Debug Show New Decimal Value ;Convert Decimal To Hex $sNewHexTotal = Hex($iNewDecTotal, 2) ConsoleWrite(@CRLF & "New Hex Value for Com Port Octet " & $sNewHexTotal) ;Debug Show New Hex Value ;Make Changes to ComDB $aComDB[$sArraySection] = $sNewHexTotal ;_ArrayDisplay($aComDB) ;Debug Show New Array of ComDB Local $sNewReg For $i = 1 to $aComDB[0] $sNewReg &= $aComDB[$i] Next RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\COM Name Arbiter", "ComDB", "REG_BINARY", Binary("0x" & $sNewReg)) If @Error Then SetError(1, 2, 0) Return EndIf Return 1 ;Return 1 if No Errors EndFunc ;End BlockComPort ;Func StringChop Func _StringChop($string, $size) $count = Ceiling(StringLen($string)/$size) Dim $array[$count+1], $start = 1 For $i = 1 To $count $array[$i] = StringMid($string, $start, $size) $start += $size Next $array[0] = $count Return $array EndFunc ; --> End StringChop ; Hex To Binary Func _HexToBinaryString($HexValue) Local $Allowed = '0123456789ABCDEF' Local $Test,$n Local $Result = '' if $hexValue = '' then SetError(-2) Return EndIf $hexvalue = StringSplit($hexvalue,'') for $n = 1 to $hexValue[0] if not StringInStr($Allowed,$hexvalue[$n]) Then SetError(-1) return 0 EndIf Next Local $bits = "0000|0001|0010|0011|0100|0101|0110|0111|1000|1001|1010|1011|1100|1101|1110|1111" $bits = stringsplit($bits,'|') for $n = 1 to $hexvalue[0] $Result &= $bits[Dec($hexvalue[$n])+1] Next Return $Result EndFunc ;--> End Hex To Binary1 point -
@TheSaint: thanks for alerting me to the Task Scheduler where I also found additional crapware feasting on my precious CPU cycles. @t0nZ: Thanks for the suggestion; I'll try it out.1 point
-
MilenP, Glad you like it. Alas, you do need to double click to open the ListView elements for editing - but how often will you be editing them? As to the "Select all" checkbox, you can use the _GUIListViewEx_ChangeItem function to amend the element contents programmatically - so no problem to react to that request. Do not hesitate to ask if you run into any problems getting the UDF to work as you wish. M231 point
-
MilenP, Here is a quick example script to show how my UDF will allow you to do what you want: #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> #include "GUIListViewEx.au3" $hGUI = GUICreate("Test", 1220, 500) ; Create titles GUICtrlCreateLabel('Policy Name', 20, 5, 200) GUICtrlCreateLabel('Condition Name', 220, 5, 280) GUICtrlCreateLabel('Selected Value', 500, 5, 150) GUICtrlCreateLabel('Critical Threshold' & @CRLF & @CRLF & 'Value - Duration', 685, 5, 160, 40) GUICtrlCreateLabel('Warning Threshold' & @CRLF & @CRLF & 'Value - Duration', 830, 5, 160) GUICtrlCreateLabel('Where' & @CRLF & @CRLF & "Clause", 945, 5, 100, 40) GUICtrlCreateLabel('Entity' & @CRLF & @CRLF & "Names(s)" , 1045, 5, 100, 40) GUICtrlCreateLabel('Status', 1145, 5, 70) GUICtrlCreateCheckbox('Select all', 1145, 25, 90) ; Create ListView $cLV = GUICtrlCreateListView("", 10, 50, 1200, 400, $LVS_NOCOLUMNHEADER) _GUICtrlListView_SetExtendedListViewStyle($cLV, BitOR($LVS_EX_FULLROWSELECT, $LVS_EX_GRIDLINES)) GUICtrlSetBkColor($cLV, 0xC4C4C4) _GUICtrlListView_AddColumn($cLV, "", 200) _GUICtrlListView_AddColumn($cLV, "", 280) _GUICtrlListView_AddColumn($cLV, "", 150) _GUICtrlListView_AddColumn($cLV, "", 70) _GUICtrlListView_AddColumn($cLV, "", 5) _GUICtrlListView_AddColumn($cLV, "", 70) _GUICtrlListView_AddColumn($cLV, "", 70) _GUICtrlListView_AddColumn($cLV, "", 5) _GUICtrlListView_AddColumn($cLV, "", 70) _GUICtrlListView_AddColumn($cLV, "", 100) _GUICtrlListView_AddColumn($cLV, "", 100) _GUICtrlListView_AddColumn($cLV, "", 50) ; Initialise ListView $iLV_Index = _GUIListViewEx_Init($cLV) GUISetState() SplashTextOn("Loading", "Please be patient!") For $i = 1 To 5 ; Set to a big number to test scrolling - but I assume you will be adding lines in much slower time $vData = "Link_" & StringFormat("%03i", $i) & "_1|Link_" & StringFormat("%03i", $i) & "_2|SelVal|Crit_1||Crit_2|Warn_1||Warn_2|Where|Entity|On" _GUIListViewEx_Insert($vData, False, True) Next SplashOff() ; Set cols 0 & 1 to run a user function when double clicked _GUIListViewEx_SetEditStatus($iLV_Index, "0;1", 9, _Link) ; Set these columns to be editable when double clicked _GUIListViewEx_SetEditStatus($iLV_Index, "2;3;5;6;8;9;10", 1, 0) ; Set column 11 to open a 2 item non-editable combo when double clicked _GUIListViewEx_SetEditStatus($iLV_Index, "11", 2, "On|Off", 3) ; Get the UDF magic to work! _GUIListViewEx_MsgRegister() While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit EndSwitch ; Allow editing of selected columns to occur - this can be expanded later to cover the $ES_NUMBER requirement _GUIListViewEx_EventMonitor() WEnd ; The user function called when cols 0 & 1 are double clicked - you can do pretty much what you want in here Func _Link($hLV_Handle, $iLV_Index, $iRow, $iCol) $sText = _GUICtrlListView_GetItemText($hLV_Handle, $iRow, $iCol) Switch $iCol Case 0 MsgBox($MB_SYSTEMMODAL, "Link_1 Func", $sText) Case 1 MsgBox($MB_SYSTEMMODAL, "Link_2 Func", $sText) EndSwitch EndFunc I hope it shows clearly what you can do with the UDF - and that the ListView is scrollable even with a large number of entries. Loading large numbers of lines takes a while at the moment because we are loading each line separately - in a more polished script we can speed this up considerably using other UDF functions. As to why your 4000 control script was slow - you are asking AutoIt to do a lot when it has to manage so many controls. By using this ListView we are getting Windows itself to do all the "heavy lifting", which makes it much faster and smoother. M231 point
-
MEmu Emulator
hoangvu0905 reacted to ViciousXUSMC for a topic
I used Nox for a while. I found automation was much cleaner and better using ADB (Android Debug Bridge) than trying to automate the Emuator itself, it could launch applications even if they were not showing on screen. My automation was to auto launch a program, and detect if it crashed and re-launch it. Memu should support the same kind of setup. BTW: YOu may want to start your own tread rather than posting on one a year old, there is not a high chance the same people are watching the thread and ready to answer.1 point -
Naming Excel Sheet
pixelsearch reacted to water for a topic
There is no need to save/reopen the workbook before you can work with it. Use the following code to rename a worksheet: $oWorkbook_PRV_HW.Sheets(n).Name = "new name" ; n can be the number of the sheet or the name in quotes like "Old Name"1 point -
Wait until key is released: #include <Misc.au3> #include <MsgBoxConstants.au3> #include <Timers.au3> #include <Date.au3> #include <File.au3> #include <Clipboard.au3> #include <GUIConstantsEx.au3> #include <SendMessage.au3> #include <WindowsConstants.au3> #include <FileConstants.au3> #include <Array.au3> Global $g_idMemo, $g_hNext = 0 Global $Timeout = 10 Global $CopyTime Global $CurrentTime Global $LogDir = @UserProfileDir & "\Appdata\Roaming\Cliplog" Global $LogBackup = @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup" Global $IsPasted = True Local $LogFile = @UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog.txt" Local $FileCreateDate = FileGetTime($LogFile, 1) If FileExists($LogDir) Then If FileExists($LogFile) Then If $FileCreateDate[1] < @MON Or $FileCreateDate[0] < @YEAR Then FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog_" & @MDAY & @MON & @YEAR & ".txt", 8) If FileExists($LogBackup) Then FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog" & "\*.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup", $FC_OVERWRITE + $FC_CREATEPATH) Else DirCreate($LogBackup) FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog" & "\*.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup", $FC_OVERWRITE + $FC_CREATEPATH) EndIf EndIf Else Example() EndIf Else DirCreate($LogDir) EndIf Example() Func Example() Local $hGUI ; Create GUI $hGUI = GUICreate("Clipboard", 600, 400) $g_idMemo = GUICtrlCreateEdit("", 2, 2, 596, 396, $WS_VSCROLL) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState(@SW_SHOWMINIMIZED) ; Initialize clipboard viewer $g_hNext = _ClipBoard_SetViewer($hGUI) GUIRegisterMsg($WM_CHANGECBCHAIN, "WM_CHANGECBCHAIN") GUIRegisterMsg($WM_DRAWCLIPBOARD, "WM_DRAWCLIPBOARD") MemoWrite("Clipboard utility ....: AON") MemoWrite("Clipboard owner ....: " & @UserName) MemoWrite(":...............................................................................:") ; Loop until the user exits. Local $GetMsg = True While 1 Local $currMsg = GUIGetMsg() Clear() ; if $currMsg = $GUI_EVENT_CLOSE then $GetMsg = False WEnd ; Shut down clipboard viewer _ClipBoard_ChangeChain($hGUI, $g_hNext) EndFunc ;==>Example ; Write message to memo Func MemoWrite($sMessage = "", $IsDate = True) If $IsDate Then GUICtrlSetData($g_idMemo, _Now() & " " & $sMessage & @CRLF, 1) Else GUICtrlSetData($g_idMemo, $sMessage & @CRLF, 1) EndIf EndFunc ;==>MemoWrite ; Handle $WM_CHANGECBCHAIN messages Func WM_CHANGECBCHAIN($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg ; Show that message was received MemoWrite("***** $WM_CHANGECBCHAIN *****") ; If the next window is closing, repair the chain If $wParam = $g_hNext Then $g_hNext = $lParam ; Otherwise pass the message to the next viewer ElseIf $g_hNext <> 0 Then _SendMessage($g_hNext, $WM_CHANGECBCHAIN, $wParam, $lParam, 0, "hwnd", "hwnd") EndIf EndFunc ;==>WM_CHANGECBCHAIN ; Handle $WM_DRAWCLIPBOARD messages Func WM_DRAWCLIPBOARD($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg ; Display any text on clipboard MemoWrite(_ClipBoard_GetData()) ; Pass the message to the next viewer If $g_hNext <> 0 Then _SendMessage($g_hNext, $WM_DRAWCLIPBOARD, $wParam, $lParam) EndFunc ;==>WM_DRAWCLIPBOARD Func Clear() If _IsPressed("11") And _IsPressed("56") Then If Not $IsPasted Then $CMD = "echo off | clip" ;you start your script here RunWait(@ComSpec & " /c " & $CMD, @WindowsDir, @SW_SHOW) EndIf $IsPasted = True Else If _IsPressed("11") And _IsPressed("43") Then Global $sData = ClipGet() ; Retrieve the data stored in the clipboard. $CopyTime = _NowCalc() ; Store copytime to variable ;Msgbox ($MB_SYSTEMMODAL, "", "The following tmp" & @CRLF & ClipGet() , $Timeout) _FileWriteLog($LogFile, $sData) ;Write Log to log file $IsPasted = False While _IsPressed("11") And _IsPressed("43") Sleep(250) WEnd EndIf $CurrentTime = _NowCalc() If Not $IsPasted Then If _DateDiff('s', $CopyTime, $CurrentTime) > 10 And _DateDiff('s', $CopyTime, $CurrentTime) < 12 Then $CMD = "echo off | clip" ;you start your script here RunWait(@ComSpec & " /c " & $CMD, @WindowsDir, @SW_SHOW) $IsPasted = True EndIf EndIf If _IsPressed("11") And _IsPressed("10") And _IsPressed("23") Then Exit EndIf EndIf Break(0) ; Disable Break/Pause/Exit of script GUIGetMsg() ; to cool out CPU when CTRL+V is not pressed. It was not kept in loop of while so that it can be called everytime but not when CTRL+ V is pressed.If not added then CPU usage will be 25% EndFunc ;==>Clear Last text <> Current text: #include <Misc.au3> #include <MsgBoxConstants.au3> #include <Timers.au3> #include <Date.au3> #include <File.au3> #include <Clipboard.au3> #include <GUIConstantsEx.au3> #include <SendMessage.au3> #include <WindowsConstants.au3> #include <FileConstants.au3> #include <Array.au3> Global $g_idMemo, $g_hNext = 0 Global $Timeout = 10 Global $CopyTime Global $CurrentTime Global $LogDir = @UserProfileDir & "\Appdata\Roaming\Cliplog" Global $LogBackup = @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup" Global $IsPasted = True Local $LogFile = @UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog.txt" Local $FileCreateDate = FileGetTime($LogFile, 1) Global $LastText = "" If FileExists($LogDir) Then If FileExists($LogFile) Then If $FileCreateDate[1] < @MON Or $FileCreateDate[0] < @YEAR Then FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Cliplog_" & @MDAY & @MON & @YEAR & ".txt", 8) If FileExists($LogBackup) Then FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog" & "\*.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup", $FC_OVERWRITE + $FC_CREATEPATH) Else DirCreate($LogBackup) FileMove(@UserProfileDir & "\Appdata\Roaming\Cliplog" & "\*.txt", @UserProfileDir & "\Appdata\Roaming\Cliplog\Backup", $FC_OVERWRITE + $FC_CREATEPATH) EndIf EndIf Else Example() EndIf Else DirCreate($LogDir) EndIf Example() Func Example() Local $hGUI ; Create GUI $hGUI = GUICreate("Clipboard", 600, 400) $g_idMemo = GUICtrlCreateEdit("", 2, 2, 596, 396, $WS_VSCROLL) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState(@SW_SHOWMINIMIZED) ; Initialize clipboard viewer $g_hNext = _ClipBoard_SetViewer($hGUI) GUIRegisterMsg($WM_CHANGECBCHAIN, "WM_CHANGECBCHAIN") GUIRegisterMsg($WM_DRAWCLIPBOARD, "WM_DRAWCLIPBOARD") MemoWrite("Clipboard utility ....: AON") MemoWrite("Clipboard owner ....: " & @UserName) MemoWrite(":...............................................................................:") ; Loop until the user exits. Local $GetMsg = True While 1 Local $currMsg = GUIGetMsg() Clear() ; if $currMsg = $GUI_EVENT_CLOSE then $GetMsg = False WEnd ; Shut down clipboard viewer _ClipBoard_ChangeChain($hGUI, $g_hNext) EndFunc ;==>Example ; Write message to memo Func MemoWrite($sMessage = "", $IsDate = True) If $IsDate Then GUICtrlSetData($g_idMemo, _Now() & " " & $sMessage & @CRLF, 1) Else GUICtrlSetData($g_idMemo, $sMessage & @CRLF, 1) EndIf EndFunc ;==>MemoWrite ; Handle $WM_CHANGECBCHAIN messages Func WM_CHANGECBCHAIN($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg ; Show that message was received MemoWrite("***** $WM_CHANGECBCHAIN *****") ; If the next window is closing, repair the chain If $wParam = $g_hNext Then $g_hNext = $lParam ; Otherwise pass the message to the next viewer ElseIf $g_hNext <> 0 Then _SendMessage($g_hNext, $WM_CHANGECBCHAIN, $wParam, $lParam, 0, "hwnd", "hwnd") EndIf EndFunc ;==>WM_CHANGECBCHAIN ; Handle $WM_DRAWCLIPBOARD messages Func WM_DRAWCLIPBOARD($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg ; Display any text on clipboard MemoWrite(_ClipBoard_GetData()) ; Pass the message to the next viewer If $g_hNext <> 0 Then _SendMessage($g_hNext, $WM_DRAWCLIPBOARD, $wParam, $lParam) EndFunc ;==>WM_DRAWCLIPBOARD Func Clear() If _IsPressed("11") And _IsPressed("56") Then If Not $IsPasted Then $CMD = "echo off | clip" ;you start your script here RunWait(@ComSpec & " /c " & $CMD, @WindowsDir, @SW_SHOW) EndIf $IsPasted = True Else If _IsPressed("11") And _IsPressed("43") Then Global $sData = ClipGet() ; Retrieve the data stored in the clipboard. $CopyTime = _NowCalc() ; Store copytime to variable ;Msgbox ($MB_SYSTEMMODAL, "", "The following tmp" & @CRLF & ClipGet() , $Timeout) If $LastText <> $sData Then _FileWriteLog($LogFile, $sData) ;Write Log to log file $IsPasted = False $LastText = $sData EndIf $CurrentTime = _NowCalc() If Not $IsPasted Then If _DateDiff('s', $CopyTime, $CurrentTime) > 10 And _DateDiff('s', $CopyTime, $CurrentTime) < 12 Then $CMD = "echo off | clip" ;you start your script here RunWait(@ComSpec & " /c " & $CMD, @WindowsDir, @SW_SHOW) $IsPasted = True EndIf EndIf If _IsPressed("11") And _IsPressed("10") And _IsPressed("23") Then Exit EndIf EndIf Break(0) ; Disable Break/Pause/Exit of script GUIGetMsg() ; to cool out CPU when CTRL+V is not pressed. It was not kept in loop of while so that it can be called everytime but not when CTRL+ V is pressed.If not added then CPU usage will be 25% EndFunc ;==>Clear1 point
-
Summary The program which I will abbreviate as ASDV was created with the intention of easily archiving AutoIt scripts that are loaded in a programming editor. Sometimes you may find many scripts open in your editor and may want an easy way to store them and release them from the editor. ASDV takes a single path parameter so the editor can pass the path to the script and the ASDV will insert it into a SQLite database. The whole process should be rather simple to store the script. Once done and satisfied, then you can close the script in the editor and have fewer scripts open at one time. ASDV allows you access to the stored script at any time. You can make routine backups of the database to prevent any data loss. Backups can be compressed by zip or similar and may take up a little amount of space. ASDV supports adding scripts as mentioned previous and also does the following features when you right click on the title listbox. About title - Output of information about the title selected from the database Copy title - Copies for e.g. "Example 1" to the clipboard Copy script - Copies the whole script in the viewer to the clipboard Delete title and script - Removes the entry permanently from the database RunWait script - Writes the viewed script to a file in @TempDir and runs it from there with @AutoItExe Save script - Saves the viewed script to an au3 file View script in your web browser - Perhaps a nicer way to view a script with some coloring done on keywords Font size - For preference of those with great eye sight or near blind Download Au3 Script Database.zip Under terms of GPL3 Requires SQLite.au3 which will is a standard include in AutoIt3. SQLite3.dll if you do not have it already here. Tested with AutoIt 3.3.8.1 + and latest SQLite3.dll. Further details can be found in the help file included. Homepage can be found here.1 point
-
Hi, Here is what Andreik was thinking about : #include <WindowsConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <WinAPI.au3> Opt("GUIOnEventMode", 1) GUICreate("toto") GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit") $tbMyInputNumber = GUICtrlCreateEdit("", 10, 10, 100, 20, $ES_AUTOHSCROLL) GUIRegisterMsg($WM_COMMAND, "WM_COMMAND") GUISetState() While 1 Sleep(1000) WEnd Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam) Local $iCode = BitShift($wParam, 16) Local $iIDFrom = _WinAPI_LoWord($wParam) Switch $iIDFrom Case $tbMyInputNumber Switch $iCode Case $EN_UPDATE Local $sWMCOMMAND_MyInputNumberRead = GUICtrlRead($tbMyInputNumber) Local $sWMCOMMAND_MyInputNumberLastChar = StringRight($sWMCOMMAND_MyInputNumberRead, 1) Local $aWMCOMMAND_MyInputNumberDotSplit = StringSplit($sWMCOMMAND_MyInputNumberRead, ".") If $aWMCOMMAND_MyInputNumberDotSplit[0] > 2 Or (Not StringIsInt($sWMCOMMAND_MyInputNumberLastChar) And $sWMCOMMAND_MyInputNumberLastChar <> ".") Then GUICtrlSetData($tbMyInputNumber, StringTrimRight($sWMCOMMAND_MyInputNumberRead, 1)) EndIf EndSwitch EndSwitch Return $GUI_RUNDEFMSG EndFunc Func _Exit() Exit EndFunc And I'm sure this can be more clear with a RegExp test. Br, FireFox.1 point
-
Hey I just made a more Better Way for ClipBoard Monitoring I havent added the save and send Functions Its very Easy Ahead to Modify #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.6.1 Author: Zedna Modified: Phoenix XL Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include <GUIConstants.au3> #include <WindowsConstants.au3> Global $origHWND,$lastCopied='',$WM_CLIPUPDATE=0x031D,$DefMsG='__•¯¯' $gui = GUICreate("Clip Hook",400,400,-1,-1,BitOR($WS_CAPTION,$WS_SYSMENU)) Global $label=GUICtrlCreateLabel('Clipboard Contains',30,30,340,30) Global $label1=GUICtrlCreateEdit('Clipboard Contains',30,80,340,210) ; remember last clip viewer in queue and set our GUI as first in queue $origHWND = DLLCall("user32.dll","int","AddClipboardFormatListener","hwnd",$gui) $origHWND = $origHWND[0] GUIRegisterMsg($WM_CLIPUPDATE,"OnClipBoardChange") WinSetOnTop($gui,'',1) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd Exit Func OnClipBoardChange($hWnd, $Msg, $wParam, $lParam) ; do what you need when clipboard changes _write(ClipGet()) EndFunc Func _write($data) If $data<>$lastCopied Then $lastCopied=$data Return GUICtrlSetData($label1,$data) Else Return $DefMsG EndIf EndFunc1 point
-
Hey !! I added a Format Listener Instead of a ClipBoardViewer Windows Its a bit less complicated coz there is no need of the maintenance of the Chains..... Here is the code #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.6.1 Author: Zedna (Modified By Me) Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include <GUIConstants.au3> #include <WindowsConstants.au3> Global $origHWND,$lastCopied='',$WM_CLIPUPDATE=0x031D,$DefMsG='__•¯¯' $gui = GUICreate("Clip Hook",400,400,-1,-1,BitOR($WS_CAPTION,$WS_SYSMENU)) Global $label=GUICtrlCreateLabel('Clipboard Contains',30,30,340,30) Global $label1=GUICtrlCreateEdit('Clipboard Contains',30,80,340,210) ; remember last clip viewer in queue and set our GUI as first in queue $origHWND = DLLCall("user32.dll","int","AddClipboardFormatListener","hwnd",$gui) $origHWND = $origHWND[0] GUIRegisterMsg($WM_CLIPUPDATE,"OnClipBoardChange") WinSetOnTop($gui,'',1) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd Exit Func OnClipBoardChange($hWnd, $Msg, $wParam, $lParam) ; do what you need when clipboard changes _write(ClipGet()) EndFunc Func _write($data) If $data<>$lastCopied Then $lastCopied=$data Return GUICtrlSetData($label1,$data) Else Return $DefMsG EndIf EndFunc1 point
-
view tables and their contents on a SQL Server database, locally or on a network. The login information is stored without encryption, in a file named SQLDBViewer.ini. If this is a problem, comment out the calls to SaveINI(), and you will have to enter the info every time you start the script. This has been used with a SQL Server 2008 database where tables belong to various schemas, on XP SP3, and win2008R1. Ctrl-alt-c will copy the query, the name of the columns and the returned data so you can paste that info elsewhere. F5 will run the query again if you edit it. Please feel free to improve on this. The code is displayed here, and also attached below. The latest link is at the bottom. Enjoy. Opt('MustDeclareVars', 1) Opt("GUIOnEventMode", 1) #include <GUIConstantsEx.au3> #include <ComboConstants.au3> #include <EditConstants.au3> #include <GUIListBox.au3> #Include <GuiListView.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <Array.au3> Global $g_eventerror = 0 Global $oMyError = 0 ;Dim $DEBUG = True Dim $DEBUG = False Dim $arConnectInfo[1] $arConnectInfo[0] = 0 Dim $FormHwnd, $LabelID, $cboConnInfo, $btnConnect Dim $gbConInfo, $lblServer, $txtServer, $lblCat, $txtCatalog, $lblUser, $txtuser, $lblPasword, $txtPassword Dim $gbTableListDisplay, $lbTables Dim $gbTableDisplay, $pb, $txtQuery, $lvTable, $cm, $cmCopyColNamesAndRow, $cmCopyRow, $lblSep Dim $IniBuf = "" Dim $SelectedConnectionInformation = "" Dim $bCheckConInfo = False Dim $bCheckSelectedTable = False Dim $CurrentTableName = "" ; the table that is currently selected. Will change if a new selection is made. Dim $bShowUpDnButtons = False ; true to show up and down separator buttons, false to hide them Dim $SleepTimeMS = 300 Dim $MouseYLocation = -1 Dim $TableData = "";includes the query, the column names and tab-separated column values for CRLF-separated records, populated when a query is run HotKeySet ( "^!c", "CopyData" );ctrl-alt-c HotKeySet ( "{F5}", "RunUserQuery" ) Main() Func Main() ReadIniData() ; read stored connection information DoUI() ; create the UI and handle user actions on the UI EndFunc ;-----------UI Functions----------- Func DoUI() Dim $font = "Comic Sans MS" ;~ GUISetFont ( 9, 400, 1, $font ) $FormHwnd = GUICreate ( "SQL Server Tool", @DesktopWidth / 2 - 175, 200, 200, @DesktopHeight / 2 - 45, 0x00040000 + 0x00010000, 0x00000018 ) ; $WS_SIZEBOX + $WS_MAXIMIZEBOX, WS_EX_ACCEPTFILES GUISetBkColor ( 0x00E0FFFF ) ;window backgrd = light blue $LabelID = GUICtrlCreateLabel ( "Select Database", 2, 2, 200 ) GUICtrlSetResizing ( $LabelID, $GUI_DOCKLEFT + $GUI_DOCKWIDTH + $GUI_DOCKTOP ) $cboConnInfo = GUICtrlCreateCombo ( "", 2, 22, 118, 25, BitOR ( $CBS_DROPDOWN,$CBS_AUTOHSCROLL ) ) GUICtrlSetResizing ( $cboConnInfo, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKSIZE ) if $arConnectInfo [ 0 ] > 0 Then Dim $ConnBuffer = _ArrayToString ( $arConnectInfo ) $ConnBuffer = StringRight ( $ConnBuffer, StringLen ( $ConnBuffer ) - StringInStr ( $ConnBuffer, @CRLF ) - 2 ) GUICtrlSetData ( $cboConnInfo, $ConnBuffer ) EndIf $btnConnect = GUICtrlCreateButton ( "New Connection", 120, 20, 98, 22 ) GUICtrlSetOnEvent($btnConnect, "ConnectBtnOnClick") GUICtrlSetResizing ( $btnConnect, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKSIZE ) #region Connection Infomation groupbox $gbConInfo = GUICtrlCreateGroup("Connection Information", 220, 8, 260, 81) GUICtrlSetResizing ( $gbConInfo, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $gbConInfo, $GUI_HIDE ) $lblServer = GUICtrlCreateLabel("Server", 230, 24, 35, 17) GUICtrlSetResizing ( $lblServer, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $lblServer, $GUI_HIDE ) $txtServer = GUICtrlCreateInput("", 270, 24, 70, 21) GUICtrlSetResizing ( $txtServer, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $txtServer, $GUI_HIDE ) $lblCat = GUICtrlCreateLabel("Catalog", 230, 56, 40, 17) GUICtrlSetResizing ( $lblCat, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $lblCat, $GUI_HIDE ) $txtCatalog = GUICtrlCreateInput("", 270, 56, 70, 21) GUICtrlSetResizing ( $txtCatalog, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $txtCatalog, $GUI_HIDE ) $lblUser = GUICtrlCreateLabel("User", 350, 24, 26, 17) GUICtrlSetResizing ( $lblUser, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $lblUser, $GUI_HIDE ) $txtuser = GUICtrlCreateInput ( "", 400, 24, 70, 21 ) GUICtrlSetResizing ( $txtuser, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $txtuser, $GUI_HIDE ) $lblPasword = GUICtrlCreateLabel("Password", 350, 56, 50, 17) GUICtrlSetResizing ( $lblPasword, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $lblPasword, $GUI_HIDE ) $txtPassword = GUICtrlCreateInput ( "", 400, 56, 70, 21, $ES_PASSWORD ) GUICtrlSetResizing ( $txtPassword, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $txtPassword, $GUI_HIDE ) GUICtrlCreateGroup("", -99, -99, 1, 1) #endregion End Connection Infomation groupbox #region Available Table List groupgbox $gbTableListDisplay = GUICtrlCreateGroup("Table List", 2, 42, 210, @DesktopHeight / 2 - 376) GUICtrlSetResizing ( $gbTableListDisplay, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKBOTTOM ) GUICtrlSetState ( $gbTableListDisplay, $GUI_HIDE ) $lbTables = GUICtrlCreateList ( "", 4, 56, 206, @DesktopHeight / 2 - 392, $LBS_NOINTEGRALHEIGHT + $WS_VSCROLL + $LBS_SORT ) GUICtrlSetResizing ( $lbTables, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKBOTTOM ) GUICtrlSetState ( $lbTables, $GUI_HIDE ) GUICtrlCreateGroup("", -99, -99, 1, 1) #endregion Available Table List groupgbox #region Table display groupbox $gbTableDisplay = GUICtrlCreateGroup("Table", 220, 2, @DesktopWidth / 2 - 400, @DesktopHeight / 2 - 336) GUICtrlSetResizing ( $gbTableDisplay, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKWIDTH + $GUI_DOCKRIGHT + $GUI_DOCKBOTTOM ) GUICtrlSetState ( $gbTableDisplay, $GUI_HIDE ) $pb = GUICtrlCreateProgress ( 222, 16, @DesktopWidth / 2 - 404, 17, 0x01 ) ; 0x01 = $PBS_SMOOTH GUICtrlSetColor ( $pb, 0x00FF00 ); set progress bar color to green GUICtrlSetState ( $pb, $GUI_HIDE ) $txtQuery = GUICtrlCreateEdit ( "", 222, 16, @DesktopWidth / 2 - 404, 60, $ES_MULTILINE ) GUICtrlSetResizing ( $txtQuery, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKRIGHT + $GUI_DOCKHEIGHT ) GUICtrlSetState ( $txtQuery, $GUI_HIDE ) $lblSep = GUICtrlCreateLabel ( "", 220, 72, @DesktopWidth / 2 - 402, 12 ) GUICtrlSetResizing ( $lblSep, $GUI_DOCKLEFT + $GUI_DOCKHEIGHT + $GUI_DOCKRIGHT ) GUICtrlSetBkColor ( $lblSep, 0x808080 ) GUICtrlSetCursor ( $lblSep, 11 ) GUICtrlSetState ( $lblSep, $GUI_HIDE ) $lvTable = GUICtrlCreateListView ( "", 222, 80, @DesktopWidth / 2 - 404, 98 ) GUICtrlSetResizing ( $lvTable, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKRIGHT + $GUI_DOCKBOTTOM ) GUICtrlSetState ( $lvTable, $GUI_HIDE ) $cm = GUICtrlCreateContextMenu ( $lvTable ) $cmCopyColNamesAndRow = GUICtrlCreateMenuItem ( "Copy Columns + Row", $cm ) GUICtrlSetOnEvent($cmCopyColNamesAndRow, "CopyColNamesAndRowOnClick") $cmCopyRow = GUICtrlCreateMenuItem ( "Copy Row", $cm ) GUICtrlSetOnEvent($cmCopyRow, "CopyRowOnClick") GUICtrlCreateGroup("", -99, -99, 1, 1) #endregion Table display groupbox GUISetOnEvent($GUI_EVENT_CLOSE, "OnExit") GUISetState() ; display the GUI While 1 if StringLen ( GUICtrlRead ( $cboConnInfo ) ) = 0 Then GUICtrlSetData ( $btnConnect, "New Connection" ) Else GUICtrlSetData ( $btnConnect, "Connect" ) EndIf if $bCheckConInfo Then CheckConInfo() EndIf if $bCheckSelectedTable Then ; a query is displayed with its data. Watch for a new table selection to update the query an data display. CheckTableSelection() ; if the mouse is between the query edit box and the data listview, change the mouse cursor SetMouseCursor() EndIf Sleep ( $SleepTimeMS ) WEnd GUIDelete( $FormHwnd ) Exit EndFunc Func ConnectBtnOnClick() $SelectedConnectionInformation = GUICtrlRead ( $cboConnInfo ) if StringLen ( $SelectedConnectionInformation ) = 0 And StringLen ( GUICtrlRead ( $txtPassword ) ) > 0 Then $SelectedConnectionInformation = GUICtrlRead ( $txtServer ) & @TAB & GUICtrlRead ( $txtCatalog ) & @TAB & GUICtrlRead ( $txtUser ) & @TAB & GUICtrlRead ( $txtPassword ) EndIf Dim $InfoItemNumber = _ArrayTokenNum ( $SelectedConnectionInformation, @TAB ) if $InfoItemNumber < 4 Then FillConInfoWithExistingInfo ( $InfoItemNumber ) DisplayConInfoGroupBox ( $GUI_SHOW ) GUICtrlSetState ( $btnConnect, $GUI_DISABLE ) $bCheckConInfo = True Else $bCheckConInfo = False ; stop checking connection info user filled controls ClearConInfoGBData () ; clear the server, catalog, user and password edit boxes and hide the connection info groupbox with its contents DisplayConInfoGroupBox ( $GUI_HIDE ) if ShowDBTables() Then SaveIni() EndIf EndIf EndFunc Func CopyColNamesAndRowOnClick() Dim $ItemText = "" Dim $arColInfo [ 9 ] Dim $SelNum = _GUICtrlListView_GetSelectedCount ( $lvTable ) Dim $ColCount = _GUICtrlListView_GetColumnCount ( $lvTable ) for $i = 0 to $ColCount - 1 $arColInfo = _GUICtrlListView_GetColumn ( $lvTable, $i ) if $i = 0 Then $ItemText = $arColInfo [ 5 ] Else $ItemText &= @TAB & $arColInfo [ 5 ] EndIf Next $ItemText &= @CRLF if $SelNum > 0 Then Dim $SelRow = _GUICtrlListView_GetSelectedIndices ( $lvTable ) if StringLen ( $SelRow ) > 0 Then for $Col = 0 to $ColCount - 1 if $Col = 0 Then $ItemText &= _GUICtrlListView_GetItemText ( $lvTable, $SelRow * 1, $Col ) Else $ItemText &= @TAB & _GUICtrlListView_GetItemText ( $lvTable, $SelRow * 1, $Col ) EndIf Next EndIf EndIf ClipPut ( "" ) ClipPut ( $ItemText ) EndFunc Func CopyRowOnClick() Dim $SelNum = _GUICtrlListView_GetSelectedCount( $lvTable ) if $SelNum > 0 Then Dim $SelRow = _GUICtrlListView_GetSelectedIndices ( $lvTable ) if StringLen ( $SelRow ) > 0 Then Dim $ItemText = "" for $Col = 0 to _GUICtrlListView_GetColumnCount ( $lvTable ) - 1 if $Col = 0 Then $ItemText &= _GUICtrlListView_GetItemText ( $lvTable, $SelRow * 1, $Col ) Else $ItemText &= @TAB & _GUICtrlListView_GetItemText ( $lvTable, $SelRow * 1, $Col ) EndIf Next ClipPut ( "" ) ClipPut ( $ItemText ) EndIf EndIf EndFunc Func OnExit() Exit EndFunc ;-----------Helper Functions------------- Func _ArrayTokenNum ( $SeparatedString, $Separator ) if StringInStr ( $SeparatedString, $Separator ) = 0 Then if StringLen ( $SeparatedString ) > 0 Then Return 1 Else Return 0 EndIf Else Dim $arTokens = StringSplit ( $SeparatedString, $Separator, 1 ) Return $arTokens [ 0 ] EndIf EndFunc Func CheckConInfo() if StringLen ( GUICtrlRead ( $txtCatalog ) ) > 0 And _ StringLen ( GUICtrlRead ( $txtUser ) ) > 0 And _ StringLen ( GUICtrlRead ( $txtPassword ) ) > 0 Then GUICtrlSetState ( $btnConnect, $GUI_ENABLE ) GUICtrlSetData ( $btnConnect, "Connect" ) ; update the button text to let user know they can try connecting $SelectedConnectionInformation = GUICtrlRead ( $txtServer ) & @TAB & GUICtrlRead ( $txtCatalog ) & @TAB & GUICtrlRead ( $txtUser ) & @TAB & GUICtrlRead ( $txtPassword ) EndIf EndFunc Func CheckTableSelection() Dim $SelectedTable = GUICtrlRead ( $lbTables ) if StringLen ( $SelectedTable ) = 0 then Return ; no selection if $CurrentTableName = $SelectedTable Then Return ; no new selection GUICtrlSetData ( $txtQuery, "select * from " & $SelectedTable ) DisplayTableGroup ( $GUI_SHOW ) RunUserQuery() $CurrentTableName = $SelectedTable ; set the current table for future verification of user table selection change EndFunc Func ClearConInfoGBData () GUICtrlSetData ( $txtServer, "" ) GUICtrlSetData ( $txtCatalog, "" ) GUICtrlSetData ( $txtUser, "" ) GUICtrlSetData ( $txtPassword, "" ) EndFunc ; Convert the client (GUI) coordinates to screen (desktop) coordinates Func ClientToScreen($hWnd, ByRef $x, ByRef $y) Local $stPoint = DllStructCreate("int;int") DllStructSetData($stPoint, 1, $x) DllStructSetData($stPoint, 2, $y) DllCall("user32.dll", "int", "ClientToScreen", "hwnd", $hWnd, "ptr", DllStructGetPtr($stPoint)) $x = DllStructGetData($stPoint, 1) $y = DllStructGetData($stPoint, 2) ; release Struct (not really needed as it is a local) $stPoint = 0 EndFunc Func CopyData () ClipPut ( $TableData ) EndFunc Func DisplayConInfoGroupBox ( $Setting ) GUICtrlSetState ( $gbConInfo, $Setting ) GUICtrlSetState ( $lblServer, $Setting ) GUICtrlSetState ( $txtServer, $Setting ) GUICtrlSetState ( $lblCat, $Setting ) GUICtrlSetState ( $txtCatalog, $Setting ) GUICtrlSetState ( $lblUser, $Setting ) GUICtrlSetState ( $txtUser, $Setting ) GUICtrlSetState ( $lblPasword, $Setting ) GUICtrlSetState ( $txtPassword, $Setting ) EndFunc Func DisplayTableGroup ( $Setting ) GUICtrlSetState ( $gbTableDisplay, $Setting ) GUICtrlSetState ( $txtQuery, $Setting ) GUICtrlSetState ( $lvTable, $Setting ) GUICtrlSetState ( $lblSep, $Setting ) EndFunc Func DisplayTableListGroup ( $Setting ) GUICtrlSetState ( $gbTableListDisplay, $Setting ) GUICtrlSetState ( $lbTables, $Setting ) EndFunc Func FillConInfoWithExistingInfo ( $InfoItemNumber ) if $InfoItemNumber > 0 Then Dim $arConInfoValues = StringSplit ( $SelectedConnectionInformation, @CRLF, 1 ) GUICtrlSetData ( $txtServer, $arConInfoValues [ 1 ] ) if $InfoItemNumber > 1 Then GUICtrlSetData ( $txtCatalog, $arConInfoValues [ 2 ] ) if $InfoItemNumber > 2 Then GUICtrlSetData ( $txtUser, $arConInfoValues [ 3 ] ) EndIf EndFunc Func IsValidQuery ( $Query ) ; the query can't be thouroughly checked here. Just make sure once leading and trailing spaces, tabs, CR, LF are stripped, it starts with "select " or "update " or "insert " While StringLeft ( $Query, 1 ) = " " Or StringLeft ( $Query, 1 ) = @TAB Or StringLeft ( $Query, 1 ) = @CR Or StringLeft ( $Query, 1 ) = @LF $Query = StringTrimLeft ( $Query, 1 ) WEnd While StringRight ( $Query, 1 ) = " " Or StringRight ( $Query, 1 ) = @TAB Or StringRight ( $Query, 1 ) = @CR Or StringRight ( $Query, 1 ) = @LF $Query = StringTrimRight ( $Query, 1 ) WEnd if StringLeft ( StringLower ( $Query ), 7 ) = "select " And StringLen ( $Query ) > 7 Then return True if StringLeft ( StringLower ( $Query ), 7 ) = "update " And StringLen ( $Query ) > 7 Then return True if StringLeft ( StringLower ( $Query ), 7 ) = "insert " And StringLen ( $Query ) > 7 Then return True EndFunc Func ReadIniData() if FileExists(@ScriptDir & "\" & "SQLDBViewer.ini") Then $IniBuf = FileRead ( @ScriptDir & "\SQLDBViewer.ini" ) if @error = 0 Then ; $IniBuf is of tab- and CRLCF-format. Each line contains tab separated values <server><catalog><user><password>; if it becomes necessary, will encrypt and decrypt $arConnectInfo = StringSplit ( $IniBuf, @CRLF ) EndIf EndIf EndFunc Func RecSetOpenError() if $oMyError = 0 then Return Dim $HexNumber = hex ( $oMyError.number, 8 ) Msgbox ( 0, "COM Error !", "Error number" & @LF & $HexNumber & @LF & _ "description is: " & $oMyError.windescription ) $g_eventerror = 1 ; something to check for when this function returns EndFunc ;----------------------------- ; Function RunQuery ; Input: ; SQry = string containing the SQL query ; $bFirstRowHasColumns = boolean, set to true to return the columns as the first item in the return array ; Output: ; an array where item 0 contains the size of the array, and each item contains a tab-separated list of values for one record ; Caveat: if the database returns an error for eg bad credentials, AutoIT cannot handle the error and crashes. ; This happens at the line "$oRS.open ( $Qry, $sqlCon, 3, -1)". Func RunQuery ( $Qry, $bFirstRowHasColumns = False ) Dim $sqlCon Dim $oRS Dim $ani1 Dim $intNbLignes Dim $adLockOptimistic =3 ;Verrouillage optimiste, un enregistrement à la fois. Le fournisseur utilise le verrouillage optimiste et ne verrouille les enregistrements qu'à l'appel de la méthode Update. Dim $adOpenKeyset = 1 ;Utilise un curseur à jeu de clés. Identique à un curseur dynamique mais ne permettant pas de voir les enregistrements ajoutés par d'autres utilisateurs (les enregistrements supprimés par d'autres utilisateurs ne sont pas accessibles à partir de votre Recordset). Les modifications de données effectuées par d'autres utilisateurs demeurent visibles. Dim $Ret = "" Dim $arConTokens = StringSplit ( $SelectedConnectionInformation, @TAB ) Dim $ServerName = $arConTokens [ 1 ] Dim $CatalogName = $arConTokens [ 2 ] Dim $User = $arConTokens [ 3 ] Dim $Pwd = $arConTokens [ 4 ] Dim $RetAr[2] $RetAr[0] = 0 $sqlCon = ObjCreate("ADODB.Connection") if $sqlCon = 0 Then MsgBox(0,"","failed to create a connection object") Exit EndIf $oMyError = ObjEvent("AutoIt.Error","RecSetOpenError") ; Install a custom error handler $ani1 = GUICtrlCreateAvi ( @SystemDir & "\shell32.dll", 165, 10, 50) GUISetState() GUICtrlSetState($ani1, 1) if $ServerName = "." or $ServerName = "" Then dim $ConString = "Provider=SQLOLEDB; Data Source=.\" & $CatalogName & "; Initial Catalog=" & $CatalogName & "; User ID=" & $User & "; Password=" & $Pwd & ";" $sqlCon.Open($ConString) Else $sqlCon.Open("Provider=SQLOLEDB; Data Source=" & $ServerName & "\" & $CatalogName & "; Initial Catalog=" & $CatalogName & "; User ID=" & $User & "; Password=" & $Pwd & ";") EndIf GUICtrlDelete ( $ani1 ) if $g_eventerror then Return $RetAr $oRS = ObjCreate ( "ADODB.Recordset" ) if $oRS = 0 then return $RetAr $oRS.CursorLocation = 2 ;adUseServer if StringLeft ( StringLower ( $Qry ), 7 ) = "select " Then $oRS.open ( $Qry, $sqlCon, 3, -1) ; adOpenStatic, lock type unspecified $intNbLignes = $oRS.recordCount if $intNbLignes > 0 Then $oRS.MoveFirst if $bFirstRowHasColumns = True Then for $iField = 0 to $oRS.Fields.Count - 1 if $iField = 0 Then $RetAr [ 1 ] = $oRS.Fields.Item(0).name Else $RetAr [ 1 ] &= @TAB & $oRS.Fields.Item($iField).name EndIf Next EndIf if $bFirstRowHasColumns Then ReDim $RetAr [ $intNbLignes + 2 ] $RetAr [ 0 ] = $intNbLignes + 1 Else ReDim $RetAr [ $intNbLignes + 1] $RetAr [ 0 ] = $intNbLignes EndIf For $i = 1 To $intNbLignes if ControlCommand ( "SQL Server Tool", "", "[CLASS:msctls_progress32; INSTANCE:1]", "IsVisible" ) Then GUICtrlSetData ( $pb, ($i * 100) / $intNbLignes ) EndIf for $j = 1 to $oRS.Fields.Count if $j > 1 Then if $bFirstRowHasColumns Then $RetAr [ $i + 1 ] &= @TAB & $oRS.Fields.Item($j - 1).value Else $RetAr [ $i ] &= @TAB & $oRS.Fields.Item($j - 1).value EndIf Else if $bFirstRowHasColumns Then $RetAr [ $i + 1 ] = $oRS.Fields.Item(0).value Else $RetAr [ $i ] = $oRS.Fields.Item(0).value EndIf EndIf Next $oRS.MoveNext Next EndIf $oRS.close EndIf Return $RetAr EndFunc Func RunUserQuery() ; check if part of the text in $txtQuery is selected Dim $OldClipValue = ClipGet() ClipPut("") ControlSend ( "SQL Server Tool", "", "[CLASS:Edit; INSTANCE:5]", "^c" ) Dim $Query = ClipGet() ClipPut ( $OldClipValue ); restore the clipboard old value if StringLen ( $Query ) = 0 Then $Query = GUICtrlRead ( $txtQuery ) EndIf Dim $arQryEditPos = ControlGetPos ( "SQL Server Tool", "", "[CLASS:Edit; INSTANCE:6]" ) GUICtrlSetPos ( $txtQuery, 222, 33, $arQryEditPos [ 2 ], 33) if Not IsValidQuery ( $Query ) Then MsgBox(0, "SQLDBViewer", "The query" & @LF & $Query & @LF & "is not a valid query.") $TableData = $Query Return EndIf Dim $arTableData = RunQuery ( $Query, True ) GUICtrlSetPos ( $txtQuery, 222, 16, $arQryEditPos [ 2 ], 50 ) ; fix the listview columns GUICtrlDelete ( $lvTable ); it's easier to just delete and recreate the listview than to clear it and remove its columns... ; gather the data needed to calculate where the listview should be recreated Dim $arGBPos = ControlGetPos ( "SQL Server Tool", "", "[CLASS:Button; INSTANCE:6]" ) $lvTable = GUICtrlCreateListView ( "", $arQryEditPos[0], $arQryEditPos[1] + $arQryEditPos[3] + 8, $arQryEditPos[2], $arGBPos[1] + $arGBPos[3] - $arQryEditPos[1] - $arQryEditPos[3] - 8 ) GUICtrlSetResizing ( $lvTable, $GUI_DOCKLEFT + $GUI_DOCKTOP + $GUI_DOCKRIGHT + $GUI_DOCKBOTTOM ) GUISetState() ; display the GUI including the new listview Dim $arCols = StringSplit ( $arTableData [ 1 ], @TAB ) for $iCol = 1 to $arCols [ 0 ] ; create and populate the missing column headers _GUICtrlListView_AddColumn ( $LVTable, $arCols [ $iCol ] ) Next ; show the progressbar and resize the input control to make room for it GUICtrlSetState ( $pb, $GUI_SHOW ) GUICtrlSetPos ( $pb, 222, 16, $arQryEditPos [ 2 ] - 4, 17 ) GUICtrlSetPos ( $txtQuery, 222, 33, $arQryEditPos [ 2 ], 40 );33) for $iRow = 2 to UBound ( $arTableData ) - 1 ; row 1 is the column names, skip GUICtrlSetData ( $pb, $iRow * 100 / $arTableData [ 0 ] ); show progress GUICtrlCreateListViewItem ( StringReplace ( $arTableData [ $iRow ], @TAB, "|" ), $lvTable ) Next ; hide the progressbar and restore the former size to the input control GUICtrlSetState ( $pb, $GUI_HIDE ) GUICtrlSetPos ( $txtQuery, 222, 16, $arQryEditPos [ 2 ], 57 );50 ) ;create the buffer that will store the data for copying to the clipboard $TableData = _ArrayToString ( $arTableData, @CRLF ) $TableData = StringRight ( $TableData, StringLen ( $TableData ) - StringInStr ( $TableData, @CRLF ) + 2 ) $TableData = GUICtrlRead ( $txtQuery ) & @CRLF & "--------------" & @CRLF & $TableData EndFunc Func SaveINI() if StringInStr ( @CRLF & $IniBuf & @CRLF, @CRLF & $SelectedConnectionInformation & @CRLF ) = 0 Then if StringLen ( $IniBuf ) < 8 Then $IniBuf = $SelectedConnectionInformation Else $IniBuf &= @CRLF & $SelectedConnectionInformation EndIf EndIf FileDelete( @ScriptDir & "\SQLDBViewer.ini" ) FileWrite ( @ScriptDir & "\SQLDBViewer.ini", $IniBuf ) EndFunc Func SetMouseCursor() Dim $arEdPos = ControlGetPos ( "SQL Server Tool", "", "[CLASS:Edit; INSTANCE:6]" ) Dim $arLvPos = ControlGetPos ( "SQL Server Tool", "", "[CLASS:SysListView32; INSTANCE:1]" ) Dim $arCursorLocation = GUIGetCursorInfo ( $FormHwnd ) if $arCursorLocation [ 4 ] = $lblSep Then if $arCursorLocation [ 2 ] = 1 Then ; mouse left button is down Dim $arLblSepPos = ControlGetPos ( "SQL Server Tool", "", "[CLASS:Static; INSTANCE:6]" ) if IsArray ( $arLblSepPos ) Then GUICtrlSetPos ( $lblSep, $arLblSepPos [ 0 ], $arCursorLocation [ 1 ] - 6, $arLblSepPos [ 2 ], 12 ) GUICtrlSetPos ( $txtQuery, $arEdPos [ 0 ], $arEdPos [ 1 ], $arEdPos [ 2 ], $arCursorLocation [ 1 ] - 6 - $arEdPos [ 1 ] ) GUICtrlSetPos ( $lvTable, $arLvPos [ 0 ], $arCursorLocation [ 1 ] + 6, $arLvPos [ 2 ], $arLvPos [ 3 ] + $arLvPos [ 1 ] - $arCursorLocation [ 1 ] + 6 ) $SleepTimeMS = 1 ;accelerate reaction to UI changes while dragging Else ConsoleWrite("$arLblSepPos is not an array") EndIf Else GUISetCursor ( 2, 0, $FormHwnd ) $SleepTimeMS = 300 ;restore normal sleep time while updating UI etc EndIf ElseIf $arCursorLocation [ 1 ] >= $arLvPos [ 1 ] And $arCursorLocation [ 1 ] <= $arLvPos [ 1 ] + $arLvPos [ 3 ] And $arCursorLocation [ 3 ] = 1 Then ; right mouse button down on listview, check if that's over a listview item Local $hMenu = GUICtrlGetHandle ( $cm ) ClientToScreen ( $FormHwnd, $arCursorLocation [ 0 ], $arCursorLocation [ 1 ] ) TrackPopupMenu($FormHwnd, $hMenu, $arCursorLocation [ 0 ], $arCursorLocation [ 1 ] ) Else GUISetCursor ( 2, 0, $FormHwnd ) $SleepTimeMS = 300 ;restore normal sleep time while updating UI etc EndIf EndFunc Func ShowDBTables() Dim $arTableInfo = RunQuery ( "select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES", False ) if $arTableInfo [ 0 ] > 0 Then Dim $TableList = _ArrayToString ( $arTableInfo ) $TableList = StringRight ( $TableList, StringLen ( $TableList ) - StringInStr ( $TableList, @CRLF ) - 2 );strip leading array size and CRLF if StringLeft ( $TableList, 1 ) = @TAB Then GUICtrlSetData ( $lbTables, StringReplace ( $TableList, @TAB, "" ) ); there is no schema name before the table, just display table names else GUICtrlSetData ( $lbTables, StringReplace ( $TableList, @TAB, "." ) ); the 1st column is the schema name, the tables should be of format schemaName.tableName EndIf DisplayTableListGroup ( $GUI_SHOW ) $bCheckSelectedTable = True Return True Else MsgBox(0,"","No tables, or connection failed...") Return False EndIf EndFunc Func TrackPopupMenu($hWnd, $hMenu, $x, $y) DllCall("user32.dll", "int", "TrackPopupMenuEx", "hwnd", $hMenu, "int", 0, "int", $x, "int", $y, "hwnd", $hWnd, "ptr", 0) EndFuncSQLDBViewer.au3 SQLDBViewer.au31 point
-
Escape to stop Script
MilenP reacted to jvanegmond for a topic
Here's what you do: If this is the original script: HotKeySet("{ESC}","Quit") ;Press ESC key to quit While True ;Here start main loop Sleep(20) WEnd Func Quit() Exit EndFunc Then here it is without stopping on escape: While True ;Here start main loop Sleep(20) WEnd Simple. Edit: Are you using a GUI? If so, then you must call this method to stop it exiting on escape: AutoItSetOption("GUICloseOnESC")1 point