Leaderboard
Popular Content
Showing content with the highest reputation on 04/23/2015 in all areas
-
Ok, here is what i came up with after 3-4 hours of scripting well ok, it has been long time since then, so... after an year or so of hard scripting/testing!!! (inspired by this topic)... GUICtrlSetOnHover UDF... Syntax: _GUICtrl_OnHoverRegister(ControlID [, OnHoverFunc [, OnLeaveHoverFunc [, PrimaryDownFunc [, PrimaryUpFunc [, KeepCall_PrDn_Func [, KeepCall_Hover_Func]]]]]]) ControlID can be -1 as in Build-In functions! Example: #include "GUICtrlOnHover.au3" Opt("GUIOnEventMode", 1) $Btn_Color = 0x7A9DD8 $Hover_Color = 0xFF0000 ;0x7AC5D8 $GUIMain = GUICreate("Letters Hovering Example", 570, 200) GUISetOnEvent(-3, "Quit") _CreateLetters_Proc(10, 60, 18, 20) GUICtrlCreateButton("Close", 30, 120, 100, 30) GUICtrlSetOnEvent(-1, "Quit") GUICtrlSetFont(GUICtrlCreateLabel("Letter: ", 35, 170, 200, 20), 9, 800) $Status_Label = GUICtrlCreateLabel("", 80, 171, 200, 20) GUICtrlSetColor(-1, 0xFF0000) GUICtrlSetFont(-1, 8.5, 800) GUISetState() While 1 Sleep(100) WEnd Func _CreateLetters_Proc($iLeft, $Top, $Width=15, $Height=15) Local $iLeft_Begin = $iLeft Local $iAsc_Char = 64 For $i = 0 To 25 $iLeft_Begin += 20 $iAsc_Char += 1 GUICtrlCreateButton(Chr($iAsc_Char), $iLeft_Begin, $Top, $Width, $Height) _GUICtrl_OnHoverRegister(-1, "_Hover_Func", "_Leave_Hover_Func") GUICtrlSetOnEvent(-1, "_Letter_Events") GUICtrlSetBkColor(-1, $Btn_Color) GUICtrlSetFont(-1, 6) Next EndFunc Func _Letter_Events() MsgBox(64, "Pressed", "Letter = " & GUICtrlRead(@GUI_CtrlId)) EndFunc Func _Hover_Func($iCtrlID) GUICtrlSetBkColor($iCtrlID, $Hover_Color) GUICtrlSetData($Status_Label, GUICtrlRead($iCtrlID)) Beep(1000, 20) EndFunc Func _Leave_Hover_Func($iCtrlID) GUICtrlSetBkColor($iCtrlID, $Btn_Color) GUICtrlSetData($Status_Label, "") EndFunc Func Quit() Exit EndFunc Attachments: [The archive include few nice examples, and the UDF itself of course .] * New (v2.1) (Redirection to Zip-file, 159 kb) _GUICtrlSetOnHover.html GUICtrlSetOnHover.zip GUICtrlSetOnHover_UDF.au3 GuiCtrlSetOnHover.zip GUICtrlSetOnHover_UDF_For_3.2.10.0.au3 Old Beta - GUICtrlSetOnHover_UDF_beta.zip Enjoy! P.S Thanks to piccaso for the greatest CallBack tool! Without it, this UDF would never been created! ============================================ History version:1 point
-
GuiBuilderNxt - Reboot [08/18/2016]
jcmackie reacted to jaberwacky for a topic
This is an update to GuiBuilder (CyberSlug, Roy, TheSaint, and many others) to run on the latest AutoIt Beta release. For a chronological history of GuiBuilder and other GUI designers see: >AutoIt GUI Creators (Designers). The seed of this effort is >here. Note: This is early stage software. Please help by reporting issues. ----------------------------------------------------- Now for the latest exciting installment! Tabs are now available! One tab can be added to the GUI. Move it, resize it, and right click to add a new tab item! More context menu items on the way. Also upcoming is the ability to be able to add controls to each tab item. --------------------------------------------------------- GUIBuilderNxt - Reboot.zip - Exe included. dl: 4286 Changelog: New Features and fixes: 1) Show or hide control while moving or resizing control. *Currently bugged out* 2) Option to show controls which have had their state set to hidden. 3) Properties window for each control as they are selected. This makes fine tuning a control easier. 4) A button which will resize a control's width to fit the text. Uses Melba23's _StringSize library. 5) Remembers settings from the last session. 6) GuiOnEvent mode. CyberSlug made mention of wanting to do this in the early days of GuiBuilder. 7) Maps rather than multidimensional arrays. 8) Consistent control naming, (i.e., instead of Group1, Button2, Button3, Radio4 it would now be Group1, Button1, Button2, Radio1). 9) Restructured the menubar layout per GuiBuilder Resurrected. 10) Hotkeys switched to accelerators. 11) Option to wipe the gui clear to the Edit menu. 12) Select and move multiple controls at once by holding down Ctrl or using a selection rectangle. 13) Copy, Paste and Delete multiple controls at once. 14) Solid grid background that now resizes to fit the GUI. Roadmap: 1) Get the Tab control to work correctly. *Still in progress* 2) Finish adding properties settings to the control properties window. 3) Make the code generation produce code with a better layout. 4) Common GUI templates. Ability to make your own templates too. 5) Select multiple controls and use arrow keys (or other method?) to snap the selected controls to align to the chosen edge. 6) Visual hints to tell you when you're within so many pixels from the edge of the window or control. Mimics the gui designer of Visual Basic. 7) Double click a control to edit the text. 8) Visual hints to indicate selected controls, etc. 9) Ability to create and store custom controls. Known issues: 1)Many!1 point -
GetModuleFunc.h 1. Introduction This writing describes in detail method for retrieving the address of exported function for loaded module without using any available API on either 32bit, 64bit or ARM based Windows systems. Structures definitions are taken from Microsoft SDK 7.1, unless otherwise specified. Loaded module is searched by name, not path. The code is written in form of function that has two parameters, WCHAR pointer to the module name and CHAR pointer to the function name, written in C++ and compiled using Microsoft Visual Studio Express 2013 for Windows Desktop. Basic knowledge of C++ is assumed. Attached GetModuleFunc.h has the full code for the function. 2. NT_TIB Structure defined inside winnt.h. It's the staring point for the algorithm. It includes self-referencing field - Self pointer, offset of which is used on non-ARM systems to read Thread Environment Block data. typedef struct _NT_TIB { struct _EXCEPTION_REGISTRATION_RECORD *ExceptionList; PVOID StackBase; PVOID StackLimit; PVOID SubSystemTib; #if defined(_MSC_EXTENSIONS) union { PVOID FiberData; DWORD Version; }; #else PVOID FiberData; #endif PVOID ArbitraryUserPointer; struct _NT_TIB *Self; } NT_TIB; typedef NT_TIB *PNT_TIB; 2.1. TEBThread Environment Block is chunk of memory filled with various information about the thread. TEB is defined inside winternl.h as: typedef struct _TEB { PVOID Reserved1[12]; PPEB ProcessEnvironmentBlock; PVOID Reserved2[399]; BYTE Reserved3[1952]; PVOID TlsSlots[64]; BYTE Reserved4[8]; PVOID Reserved5[26]; PVOID ReservedForOle; // Windows 2000 only PVOID Reserved6[4]; PVOID TlsExpansionSlots; } TEB, *PTEB; After the executable is loaded by the Windows PE loader and before the thread starts running, TEB is saved to fs(x86) or gs(x64 flavor) processor register. ARM systems use different technique which utilize coprocessors scheme (it's unclear whether the coprocessor is real hardware component or emulated). Self field of NT_TIB is the TEB pointer for the current thread.Even not officially documented, this behavior is observed on/for all available Windows operating systems with NT kernel. Acquiring pointer to the TEB is done using Microsoft specific compiler intrinsics: #include <winnt.h> #include <winternl.h> #if defined(_M_X64) // x64 auto pTeb = reinterpret_cast<PTEB>(__readgsqword(reinterpret_cast<DWORD>(&static_cast<NT_TIB*>(nullptr)->Self))); #elif defined(_M_ARM) // ARM auto pTeb = reinterpret_cast<PTEB>(_MoveFromCoprocessor(15, 0, 13, 0, 2)); // CP15_TPIDRURW #else // x86 auto pTeb = reinterpret_cast<PTEB>(__readfsdword(reinterpret_cast<DWORD>(&static_cast<NT_TIB*>(nullptr)->Self))); #endif Among others, one of the fields inside the TEB is pointer to the PEB (Process Environment Block). 3. PEB Process Environment Block is memory area filled with information about a process. PEB is defined inside winternl.h as: typedef struct _PEB { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID Reserved3[2]; PPEB_LDR_DATA Ldr; PRTL_USER_PROCESS_PARAMETERS ProcessParameters; PVOID Reserved4[3]; PVOID AtlThunkSListPtr; PVOID Reserved5; ULONG Reserved6; PVOID Reserved7; ULONG Reserved8; ULONG AtlThunkSListPtr32; PVOID Reserved9[45]; BYTE Reserved10[96]; PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine; BYTE Reserved11[128]; PVOID Reserved12[1]; ULONG SessionId; } PEB, *PPEB; Pointer to the PEB is read from the TEB: auto pPeb = pTeb->ProcessEnvironmentBlock; 3.1. PEB_LDR_DATAContains information about the loaded modules for the process. Ldr field of the PEB points to PEB_LDR_DATA structure, defined inside winternl.h as: typedef struct _PEB_LDR_DATA { BYTE Reserved1[8]; PVOID Reserved2[3]; LIST_ENTRY InMemoryOrderModuleList; } PEB_LDR_DATA, *PPEB_LDR_DATA; Pointer to the PEB_LDR_DATA is read from the PEB: auto pLdrData = pPeb->Ldr; 3.2. LIST_ENTRYInMemoryOrderModuleList field of the PEB_LDR_DATA is doubly-linked list that contains the loaded modules for the process, defined inside winnt.h as: typedef struct _LIST_ENTRY { struct _LIST_ENTRY *Flink; struct _LIST_ENTRY *Blink; } LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY; auto pModListHdr = &pLdrData->InMemoryOrderModuleList; 4. LDR_DATA_TABLE_ENTRYEach item in the list is a pointer to an LDR_DATA_TABLE_ENTRY structure, defined inside winternl.h as: typedef struct _LDR_DATA_TABLE_ENTRY { PVOID Reserved1[2]; LIST_ENTRY InMemoryOrderLinks; PVOID Reserved2[2]; PVOID DllBase; PVOID Reserved3[2]; UNICODE_STRING FullDllName; BYTE Reserved4[8]; PVOID Reserved5[3]; union { ULONG CheckSum; PVOID Reserved6; } DUMMYUNIONNAME; ULONG TimeDateStamp; } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; DllBase field is the base address of the loaded module.This stucture doesn't give wanted info for the module, being its name. One option is to read FullDllName which includes full path and extract module name from it. However, some independent authors give slightly different definition which include another field - BaseDllName. Modified LDR_DATA_TABLE_ENTRY struct can be defined, including BaseDllName field and freed from superfluous fields. InMemoryOrderLinks will be iterated, so that field is the top of the struct: typedef struct _LDR_DATA_TABLE_ENTRY { /*LIST_ENTRY InLoadOrderLinks;*/ LIST_ENTRY InMemoryOrderLinks; LIST_ENTRY InInitializationOrderList; PVOID DllBase; PVOID EntryPoint; PVOID Reserved3; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; 4.1. IterationGoing through the items in the list is straightforward. The last item points to the first, meaning the end is reached, hence it can be written: for (auto pModListCurrent = pModListHdr->Flink; pModListCurrent != pModListHdr; pModListCurrent = pModListCurrent->Flink) { // Get current module in list auto pModEntry = reinterpret_cast<PLDR_DATA_TABLE_ENTRY>(pModListCurrent); //... } 4.2. Reading Module NameThis data is stored in form of UNICODE_STRING. winternl.h definition is: typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; Module name lookup is case insensitive. Lengths specified inside UNICODE_STRING represent bytes, which means number of WCHAR characters is half of the numbers.One of the ways to make case insensitive comparison of the specified module name and listed one is to turn both to uppercase before comparing them: for (int i = 0; i < pModEntry->BaseDllName.Length / 2 /* length is in bytes */; ++i) { if (sModuleName[i] == '\0') // the end of the string break; else if ((sModuleName[i] & ~' ') != (pModEntry->BaseDllName.Buffer[i] & ~' ')) // case-insensitive break; else if (i == iLenModule - 1) // gone through all characters and they all matched { //... the rest of the code } } iLenModule is length of the wanted module name. It's get by counting number of characters inside the string until null-terminator is encountered: int iLenModule = 0; for (; sModuleName[iLenModule]; ++iLenModule); Comparison written in this manner allows for matching function argument L"kernel32" to listed L"kernel32.dll", which mimics to a decent degree (not completely for brevity) behavior of GetModuleHandle WinAPI function. In case of two different loaded modules whose names differs only in extensions, first listed is matched. 5. PE format walkthrough The Portable Executable (PE) format is a file format for executables, object code, DLLs, etc... It describes how and where inside the file the executable code is, import table, export table, resources, and every other data needed for loader. Exported functions are listed inside the Export Table. Reaching export table is done in few steps parsing the PE data. 5.1. IMAGE_DOS_HEADER The matching module's DllBase points to the first byte of the loaded image. PE starts with legacy DOS header defined inside winnt.h as: typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header WORD e_magic; // Magic number WORD e_cblp; // Bytes on last page of file WORD e_cp; // Pages in file WORD e_crlc; // Relocations WORD e_cparhdr; // Size of header in paragraphs WORD e_minalloc; // Minimum extra paragraphs needed WORD e_maxalloc; // Maximum extra paragraphs needed WORD e_ss; // Initial (relative) SS value WORD e_sp; // Initial SP value WORD e_csum; // Checksum WORD e_ip; // Initial IP value WORD e_cs; // Initial (relative) CS value WORD e_lfarlc; // File address of relocation table WORD e_ovno; // Overlay number WORD e_res[4]; // Reserved words WORD e_oemid; // OEM identifier (for e_oeminfo) WORD e_oeminfo; // OEM information; e_oemid specific WORD e_res2[10]; // Reserved words LONG e_lfanew; // File address of new exe header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; Therefore it can be written: auto pImageDOSHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(pModEntry->DllBase); e_lfanew is offset to a NT header. 5.2. IMAGE_NT_HEADERS Another area of PE is NT header. This is effectively the starting point of the portable executable format description. Definition and the size of it depends on bitness. For 32bit it's: typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; ...and 64bit version is: typedef struct _IMAGE_NT_HEADERS64 { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64; 5.3. IMAGE_NT_HEADERSOptionalHeader field is another structure discribing in detail PE file. It's directly followed by number of IMAGE_DATA_DIRECTORY structures. The exact number of these structures is saved inside IMAGE_NT_HEADERS as NumberOfRvaAndSizes field. For 32bit PE IMAGE_NT_HEADERS is defined as: typedef struct _IMAGE_OPTIONAL_HEADER { // // Standard fields. // WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; // // NT additional fields. // DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; ...and for 64bit version it's: typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; ULONGLONG ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; PE files generated by Microsoft tools allways create IMAGE_NUMBEROF_DIRECTORY_ENTRIES (16) IMAGE_DATA_DIRECTORY structures, 15 of which are documented in this order (winnt.h): #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 // Exception Directory #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 // Security Directory #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 // Base Relocation Table #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 // Debug Directory // IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 // (X86 usage) #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 // Architecture Specific Data #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 // RVA of GP #define IMAGE_DIRECTORY_ENTRY_TLS 9 // TLS Directory #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 // Load Configuration Directory #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 // Bound Import Directory in headers #define IMAGE_DIRECTORY_ENTRY_IAT 12 // Import Address Table #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 // Delay Load Import Descriptors #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 // COM Runtime descriptor 5.4. IMAGE_DATA_DIRECTORYDefinition is: typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; It can now be written: auto pExport = reinterpret_cast<PIMAGE_DATA_DIRECTORY>(&pImageNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]); VirtualAddress field is RVA of the directory counting from the first byte (base) of the loaded module. If both VirtualAddress and Size fields are filled then the module exports functions. 5.5. IMAGE_EXPORT_DIRECTORY Definition is (winnt.h): typedef struct _IMAGE_EXPORT_DIRECTORY { DWORD Characteristics; DWORD TimeDateStamp; WORD MajorVersion; WORD MinorVersion; DWORD Name; DWORD Base; DWORD NumberOfFunctions; DWORD NumberOfNames; DWORD AddressOfFunctions; // RVA from base of image DWORD AddressOfNames; // RVA from base of image DWORD AddressOfNameOrdinals; // RVA from base of image } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; Base is ordinal value of the first exported function.NumberOfFunctions is overall number of exported functions from the module. NumberOfNames is number of functions exported only by name. AddressOfFunctions is RVA of the array of RVAs of exported functions addresses. AddressOfNames is RVA of the array of RVAs of exported functions names. AddressOfNameOrdinals is RVA of the array of WORD values each representing index of function exported by name, into the array of addresses. It's: auto pExports = reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + pExport->VirtualAddress); 6. Getting function RVAEvery exported function is accessible by odinal value. Functions exported by name are also accessible by name. Finding function by its ordinal value is fairly simple and fast. The lowest ordinal value is Base field of IMAGE_EXPORT_DIRECTORY struct. The highest ordinal value is get by adding the number of exported functions to that number, minus one of course. If the specified ordinal value is within this range, RVA is read from the array of functions addresses: if (iOrdinal) // function is wanted by its ordinal value { // Check to see if valid ordinal value is specified if (iOrdinal >= pExports->Base && iOrdinal < pExports->Base + pExports->NumberOfFunctions) dwExportRVA = pdwBufferAddress[iOrdinal - pExports->Base]; } In case of functions exported by name, name lookup needs to be performed.The code is: // Array of functions names auto pdwBufferNames = reinterpret_cast<LPDWORD>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + pExports->AddressOfNames); // Array of functions indexes into array of addresses auto pwBufferNamesOrdinals = reinterpret_cast<LPWORD>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + pExports->AddressOfNameOrdinals); And then the loop: // Loop through all functions exported by name for (DWORD j = 0; j < pExports->NumberOfNames; ++j) { // Read the listed function name auto sFunc = reinterpret_cast<LPCSTR>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + pdwBufferNames[j]); //... } When the name of the function is matched (case sensitive) the RVA of the function will be read from pdwBufferAddress array at index read from pwBufferNamesOrdinals at loop counter value index: dwExportRVA = pdwBufferAddress[pwBufferNamesOrdinals[j]]; 6.1. Export ForwardingRVA of the function will resolve fonction's pointer. However there is one special case when the RVA offset points to a value inside the exports section and not to the function body which is normally found in some other sections of PE. When that happens, RVA will resolve to a null-terminated ASCII string value. This is called Export Forwarding. RVA is then replaced by the RVA value of the resolved function. if (dwExportRVA > pExport->VirtualAddress && dwExportRVA < pExport->VirtualAddress + pExport->Size) { // Read forwarded data. auto sForwarder = reinterpret_cast<LPCSTR>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + dwExportRVA); //... } The format of the forwarding string is: ModuleName.FunctionName or ModuleName.#OrdinalValueTo resolve the RVA of the new exported function a recursive call to this function will be used. ModuleName has to be wide string. WCHAR buffer is allocated and all characters from ModuleName portion of forwarded string copied to it: WCHAR sForwarderDll[MAX_PATH]; // Reinterpret WCHAR buffer as CHAR one auto sForwarderDll_A = reinterpret_cast<CHAR*>(sForwarderDll); // Now go through all characters for (int iPos = 0; sForwarder[iPos]; ++iPos) { // Fill WCHAR buffer reading/copying from CHAR one sForwarderDll_A[2 * iPos] = sForwarder[iPos]; // copy character sForwarderDll_A[2 * iPos + 1] = '\0'; if (sForwarder[iPos] == '.') { sForwarderDll[iPos] = '\0'; // null-terminate the ModuleName string break; } } In case forwarding string specifies function name, pointer to that string is simply a pointer to a character following the dot.For OrdinalValue version the presence of hashtek character after the dot has to be checked and the hashtag string converted to integer value before recursive call made. The full code for this is: // Allocate big enough buffer for the new module name WCHAR sForwarderDll[MAX_PATH]; LPCSTR sForwarderFunc = nullptr; DWORD dwForwarderOrdinal = 0; // Reinterpret WCHAR buffer as CHAR one auto sForwarderDll_A = reinterpret_cast<CHAR*>(sForwarderDll); // Now go through all characters for (int iPos = 0; sForwarder[iPos]; ++iPos) { // Fill WCHAR buffer reading/copying from CHAR one sForwarderDll_A[2 * iPos] = sForwarder[iPos]; // copy character sForwarderDll_A[2 * iPos + 1] = '\0'; if (sForwarder[iPos] == '.') { sForwarderDll[iPos] = '\0'; // null-terminate the ModuleName string ++iPos; if (sForwarder[iPos] == '#') { ++iPos; // skip # character // OrdinalValue is hashtag, convert ASCII string to integer value for (; sForwarder[iPos]; ++iPos) { dwForwarderOrdinal *= 10; dwForwarderOrdinal += (sForwarder[iPos] - '0'); } if (dwForwarderOrdinal > MAX_ORDINAL) // something is wrong return nullptr; // Reinterpret the ordinal value as string sForwarderFunc = reinterpret_cast<LPSTR>(dwForwarderOrdinal); break; } else { sForwarderFunc = &sForwarder[iPos]; // FunctionName follows the dot break; } } } 6.2. FinalizingOnce funcion address RVA is get, it's added to the base address and returned from the function: return reinterpret_cast<LPVOID>(reinterpret_cast<ULONG_PTR>(pImageDOSHeader) + dwExportRVA); 7. ExampleThe attached zip contains two executables compiled from the source of 1K-Mandelbrot project, written by Emil Persson. The source had no explicit License Agreement. It's modified not to use WinAPI, rather to use method desribed here to call functions from used dlls and then compiled. Beautiful examples of visualisation of complex calculations, done in efficient way using OpenGL. Requirement is OpenGL 2.0. Third example is compiled for ARM. It's simple analog Direct2D clock, the original code of which is released under Artistic License/GPL by vckzdd. GetModuleFunc_Examples.zip 8. Conclusion This method isn't usually used by executables ran from user mode. It should be avoided used for production software, because it ommits taking ownership of critical section object used by windows during load/unload actions of the module, which could result in any kind of unhandled exception. Limited speed tests show that it's faster than standard GetModuleHandle/GetProcAddress method. Mimicking WinAPI behavior is achieved to a high level for valid input, with omitted special error handling and reporting. The only major difference is unsupported full-path processing. 8.1. Anti-Virus Software considerations This method enables compiling PE files with empty imports directory. In combination with accessing fs register at TEB/PEB offset it has been observed that 18.2% of AV scanners tend to flag 32bit executables, containing no code other than this function, as malware. 64 bit and ARM executables compiled from the same source never get flagged. References: Microsoft Corporation: Microsoft Portable Executable and Common Object File Format Specification, Revision 6.0 Matt Pietrek: Under The Hood - http://www.microsoft.com/msj/archive/s2ce.aspx An In-Depth Look into the Win32 Portable Executable File Format - http://msdn.microsoft.com/en-us/magazine/bb985992.aspx An In-Depth Look into the Win32 Portable Executable File Format, Part 2 - http://msdn.microsoft.com/en-us/magazine/cc301808.aspx Mark Russinovich, David A. Solomon, Alex Ionescu : Microsoft Windows Internals, 6th edition VirusTotal: Web Service - https://www.virustotal.com/ Emil Persson: 1K-Mandelbrot - http://www.humus.name/index.php?page=3D&ID=85 vckzdd: directxcode - https://code.google.com/p/directxcode/source/browse/#svn/Direct2D/Clock1 point
-
This is an example how to access/query different kind of Databases with AutoIt. The demo contains also test Databases, so the script functions for most of the provided database connections. Databases covered here: Oracle (no demo database for this one) MS SQL Server (no demo database for this one) SQLite (requires installation of the SQLite ODBC driver software available here: http://www.ch-werner.de/sqliteodbc/ ) Of course SQLite is natively available in AutoIt but in some cases it might be preferable to use the ODBC approach accessing the database via the same scripted method, for example if you use different Databases in the same script, it is much easier to code. Excel DBase DBF MS Access CSV Text driver (semicolon delimited and comma delimited) The example script is based on Kinshima’s Oracle SQL example . I like the Dim by pack method, much better than redim one row at the time, which too slow. All the databases have the same data content (‘Timeline_of_space_exploration’) to keep the examples similar for every database. The result of each SQL will be displayed in Arraydisplay, togheter with a window containing the ADO-less connection string (yellow) and SQL. #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_Comment=Comprehensive DSN-Less Database connection demo #AutoIt3Wrapper_Res_Description=DSN-Less Database connection demo #AutoIt3Wrapper_Res_Fileversion=1.0.0.0 #AutoIt3Wrapper_Res_LegalCopyright=GreenCan #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include <array.au3> #include <MsgBoxConstants.au3> #include <WindowsConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <ButtonConstants.au3> Opt('MustDeclareVars', 1) Global $oODBC_Connection = ObjCreate("ADODB.Connection") Global $oODBC_RecordSet = ObjCreate("ADODB.Recordset") Global $bODBC_conn = False Global $oErrADODB = ObjEvent("AutoIt.Error", "_ErrADODB") Global $bConn_error = False Global $sConnectionString, $sSQL Global Const $iDark_Blue = 0x2601D3 Global Const $iLight_Green = 0xEAFFE8 Global Const $iYellow = 0xFFFF99 ; setup GUI to display SQL Global $hGUI_View_SQL = GUICreate("SQL", 500, 500, 10, 10, $WS_CAPTION);, $WS_EX_TOPMOST) Global $hConnString = GUICtrlCreateEdit("", 5, 3, 490, 38, BitOR($ES_AUTOHSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_HSCROLL)) GUICtrlSetColor(-1, $iDark_Blue) GUICtrlSetBkColor(-1, $iYellow) Global $ViewSQL = GUICtrlCreateEdit("", 5, 45, 490, 450, BitOR($ES_AUTOVSCROLL, $ES_AUTOHSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_HSCROLL, $WS_VSCROLL)) GUICtrlSetColor(-1, $iDark_Blue) GUICtrlSetBkColor(-1, $iLight_Green) GUISetState() #========== Demo ============= Global $sDatabaseLocation = @ScriptDir & "\TestDatabases" #========== Oracle ============= ;~ #cs ;~ Not demo-able except if you have an Oracle instance ;~ #ce $sConnectionString = 'DRIVER={Oracle in OraClient11g_home1};DBQ=myDatabase.world;uid=myUserID;pwd=myPassword;' $sSQL = 'SELECT sysdate AS "Sysdate Raw", to_char(sysdate, ''Dy DD/MM/YY HH24:MI'') AS "Now" FROM dual' Format_SQL($sSQL, $sConnectionString) MsgBox(0,"Oracle SQL","You require to have access to an Oracle instance and modify the connection string before proceeding without error." & @CRLF & "The current Connection string will generate a COM error.") Query($sConnectionString, $sSQL, 500, "SQL Oracle") #========== MS SQL Server ============= MsgBox(0,"MS SQL Server","You require to have access to a SQL Server instance and modify the connection string before proceeding without error." & @CRLF & "The current Connection string will generate a COM error.") $sConnectionString = 'DRIVER={SQL Server};SERVER=ServerNameorIP;DATABASE=DatabaseServer;Trusted_Connection=no;uid=myUserID;pwd=myPassword;' $sSQL = 'SELECT 18 AS "Circle Radius",round(PI() * power(18,2) ,3) AS "Surface of circle", round(PI() * 18 * 2,3) AS "Circumference of circle"' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "MS SQL Server") #========== SQLite ============= #cs Accessing SQLite via ODBC requires installation of the SQLite ODBC driver software available here: http://www.ch-werner.de/sqliteodbc/ Note: You will have to install the 32-bit driver, as far as I could test, x6' version, sqliteodbc_w64 doesn't function on my x64 Windows You can access SQLite natively FROM AutoIt For example look at my topics - SQLite Report generator http://www.autoitscript.com/forum/topic/149767-sqlite-report-generator/#entry1068258 - SQLite demonstration of native recognition of BLOB object in Listview http://www.autoitscript.com/forum/topic/150876-sqlite-demonstration-of-native-recognition-of-blob-object-in-listview/#entry1078492 #ce $sConnectionString = 'DRIVER=SQLite3 ODBC Driver;Database=' & $sDatabaseLocation & '\Timeline_of_space_exploration.xdb;LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;' ;~ $sConnectionString = 'DRIVER=SQLite3 ODBC Driver;Database=D:\SQLite\Netline.db;LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;' $sSQL = 'SELECT * FROM space_exploration;' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQLite") #========== Excel ============= #cs The sheet range to be queried has a name defined AS SpaceTable Check the Excel sheet by selecting all (Ctrl-A) #ce $sConnectionString = 'DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};dbq=' & $sDatabaseLocation & '\Timeline_of_space_exploration.xlsx;' $sSQL = 'SELECT Format (Date, ''dd-MM-yyyy'') AS "Event", Mission_Achievements AS "Mission Achievements", Country, Organization, Mission_Name AS "Mission Name" ' & _ ' FROM SpaceTable ORDER BY Date' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQL Microsoft Excel") #========== DBase DBF ============= #cs Old Borland/Clipper Database #ce $sConnectionString = 'DRIVER={Microsoft dBase Driver (*.dbf)};Dbq='& $sDatabaseLocation & ';' $sSQL = 'SELECT Format (DATE, ''dd MMM yyyy'') AS "Event", MISSION AS "Mission Achievements", Country, ORG AS "Organization", MNAME AS "Mission Name" ' & _ ' FROM SPACE.DBF WHERE (((DATE) Between #22/04/1900# And #22/04/2015# +1)) AND UCASE(Country) <> ''USA'' ORDER BY Date' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQL DBase") #========== MS Access ============= #cs The MSAccess Example.mdb is protected with following password: DatabaseSQL #ce $sConnectionString = 'DRIVER={Microsoft Access Driver (*.mdb)};Dbq=' & $sDatabaseLocation & '\Example.mdb;uid=;pwd=DatabaseSQL;' $sSQL = 'SELECT Format (Date, ''dd MMM yyyy'') AS "Event", Mission_Achievements AS "Mission Achievements", Country, Organization, Mission_Name AS "Mission Name" ' & _ ' FROM Timeline_of_space_exploration WHERE (((Date) Between #22/04/1900# And #22/04/2015# +1)) ORDER BY Date' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQL MS Access") #========== CSV Text driver, semicolon delimited ============= #cs Some variations of the same SQL requires schema.ini in the same folder AS the text file https://msdn.microsoft.com/en-us/library/windows/desktop/ms709353(v=vs.85).aspx schema.ini settings: [Timeline_of_space_exploration_semicolon.txt] ColNameHeader=True Format=Delimited(;) MaxScanRows=1 #ce $sConnectionString = 'DRIVER={Microsoft Text Driver (*.txt; *.csv)};Dbq=' & $sDatabaseLocation & ';Extensions=asc,csv,tab,txt;' $sSQL = 'SELECT Format (Date, ''dd MMM yyyy'') AS "Event", Mission_Achievements AS "Mission Achievements", Country, ' & _ 'Organization, Mission_Name AS "Mission Name" FROM Timeline_of_space_exploration_semicolon.txt ORDER BY Date' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQL Text semicolon delimited") #========== CSV Text driver, comma delimited ============= #cs schema.ini settings: [Timeline_of_space_exploration.csv] ColNameHeader=True Format=Delimited(,) DecimalSymbol=. MaxScanRows=1 #ce $sSQL = 'SELECT Format (Date, ''dd MMM yyyy'') AS "Event", Mission_Achievements AS "Mission Achievements", Country, ' & _ 'Organization, Mission_Name AS "Mission Name" FROM Timeline_of_space_exploration.csv ORDER BY Date' Query($sConnectionString, $sSQL, 500, "SQL Text comma delimited") ; USA only $sSQL = 'SELECT Format (Date, ''dd MMM yyyy'') AS "Event", Mission_Achievements AS "Mission Achievements", Country, ' & _ 'Organization, Mission_Name AS "Mission Name" FROM Timeline_of_space_exploration.csv WHERE (((Date) Between #22/04/1900# And #22/04/2015# +1)) and UCASE(Country) = ''USA''' Format_SQL($sSQL, $sConnectionString) Query($sConnectionString, $sSQL, 500, "SQL Text comma delimited - USA Only") #========== End Demo ============= Exit Func Query($sConnectionString, $sSQL, $iMaxRows, $sTitle) If _ODBC_OpenConnection($sConnectionString) Then Local $aRecords = _ODBC_GetRecords($sSQL, 500, $iMaxRows) _ODBC_CloseConnection() ; set header string Local $sHeader = "" For $i = 0 to UBound($aRecords, 2) - 1 $sHeader &= $aRecords[0][$i] & "|" Next $sHeader = StringTrimRight($sHeader, 1) ; trim of last separator _ArrayDisplay($aRecords, _ $sTitle & " - " & "Query result: " & UBound($aRecords)-1 & " rows" & (UBound($aRecords)-1 = $iMaxRows ? " (result limited to " & $iMaxRows & " rows)" : "") , _ "1:" & UBound($aRecords)-1, _ 0, _ Default, _ $sHeader) EndIf EndFunc ;==>Query Func _ExeSQL($sSQL) If Not IsObj($oODBC_Connection) Then Return -1 $oODBC_Connection.Execute($sSQL) If $oErrADODB.number Then MsgBox($MB_YESNO + $MB_ICONERROR + $MB_DEFBUTTON2, "_ExeSQL", $sSQL & @CRLF & @CRLF & 'Error. ' & @CRLF & 'Exiting.') Exit Else Return 1 EndIf EndFunc ;==>_ExeSQL Func _ODBC_CloseConnection() $bODBC_conn = False Return $oODBC_Connection.Close EndFunc ;==>_ODBC_CloseConnection Func _ODBC_OpenConnection($sConnectionString) If Not IsObj($oODBC_Connection) Then Return -1 If Not @Compiled Then ConsoleWrite ("@@ Debug(" & @ScriptLineNumber & ") : " & $sConnectionString & @CR) $oODBC_Connection.ConnectionString = ($sConnectionString) $bConn_error = False $oODBC_Connection.Open If $bConn_error = True Then Return False EndIf $bODBC_conn = True Return True EndFunc ;==>_ODBC_OpenConnection Func _ODBC_GetRecords($sSQL, $iArrayIncrement = 250, $iRows = 0) ; syntax: _ODBC_GetRecords(SQL, ArrayIncrement, MaxRows) If Not $bODBC_conn Then MsgBox($MB_OK, 'Error', 'Connection failure') Return EndIf If $iArrayIncrement = 0 Then $iArrayIncrement = 250 If Not IsObj($oODBC_Connection) Then Return -1 If Not IsObj($oODBC_RecordSet) Then Return -2 _ODBC_OpenRecordset($sSQL) Local $aRecords[1][1] If $oODBC_RecordSet.EOF = True Then _ODBC_CloseRecordSet() Return False EndIf $oODBC_RecordSet.MoveFirst Local $x = 0 ReDim $aRecords[1][$oODBC_RecordSet.Fields.Count] For $objField In $oODBC_RecordSet.Fields $aRecords[0][$x] = $objField.Name $x += 1 Next Local $iAIn = UBound($aRecords) + $iArrayIncrement ReDim $aRecords[$iAIn][$oODBC_RecordSet.Fields.Count] $oODBC_RecordSet.MoveFirst Local $y = 0 Do $x = 0 $y += 1 For $objField In $oODBC_RecordSet.Fields $aRecords[$y][$x] = $objField.Value $x += 1 Next If $y = $iAIn - 1 Then $iAIn += $iArrayIncrement ReDim $aRecords[$iAIn][$oODBC_RecordSet.Fields.Count] EndIf $oODBC_RecordSet.MoveNext If $iRows > 0 Then If $y = $iRows Then ;_ArrayDisplay($aRecords, @ScriptLineNumber) ReDim $aRecords[$y + 1][$oODBC_RecordSet.Fields.Count] ;_ArrayDisplay($aRecords, @ScriptLineNumber) Return $aRecords EndIf EndIf Until $oODBC_RecordSet.EOF ReDim $aRecords[$y + 1][$oODBC_RecordSet.Fields.Count] _ODBC_CloseRecordSet() Return $aRecords EndFunc ;==>_ODBC_GetRecords Func _ODBC_OpenRecordset($sSQL); If Not IsObj($oODBC_Connection) Then Return -1 If Not IsObj($oODBC_RecordSet) Then Return -2 Return $oODBC_RecordSet.Open($sSQL, $oODBC_Connection, 0, 1) EndFunc ;==>_ODBC_OpenRecordset Func _ODBC_CloseRecordSet() Return $oODBC_RecordSet.Close EndFunc ;==>_ODBC_CloseRecordSet Func _ErrADODB() MsgBox($MB_ICONWARNING, "ADODB COM Error", "We intercepted a COM Error !" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $oErrADODB.description & @CRLF & _ "err.windescription:" & @TAB & $oErrADODB.windescription & @CRLF & _ "err.number is: " & @TAB & Hex($oErrADODB.number, 8) & @CRLF & _ "err.lastdllerror is: " & @TAB & $oErrADODB.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $oErrADODB.scriptline & @CRLF & _ "err.source is: " & @TAB & $oErrADODB.source & @CRLF & _ "err.helpfile is: " & @TAB & $oErrADODB.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $oErrADODB.helpcontext _ ) ConsoleWrite($oErrADODB.description & @CR) $bConn_error = True Return SetError(@error, @error, 1) EndFunc ;==>_ErrADODB Func Format_SQL($sSQL, $sConnectionString) ; format SQL script a bit ; the formating does not consider UNION, Local $stempSQL, $sSQLPart1, $sSQLPart2, $sSQLPart3, $sSQLPart4, $sSQLPart5, $sSQLPart6 $stempSQL = $sSQL ; LIMIT - should be after FROM ! If StringInStr($stempSQL, "LIMIT", 0, -1) > 0 Then If StringInStr($stempSQL, "LIMIT", 0, -1) > StringInStr($stempSQL, "FROM", 0, -1) Then $sSQLPart6 = @CRLF & "LIMIT" & @CRLF & @TAB & StringTrimLeft($stempSQL, StringInStr($stempSQL, "LIMIT", 0, -1) + 5) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "LIMIT", 0, -1) + 1), 2) EndIf EndIf ; ORDER BY - should be after FROM ! If StringInStr($stempSQL, "ORDER BY", 0, -1) > 0 Then If StringInStr($stempSQL, "ORDER BY", 0, -1) > StringInStr($stempSQL, "FROM", 0, -1) Then $sSQLPart5 = @CRLF & "ORDER BY" & @CRLF & @TAB & StringTrimLeft($stempSQL, StringInStr($stempSQL, "ORDER BY", 0, -1) + 8) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "ORDER BY", 0, -1) + 1), 2) EndIf EndIf ; GROUP BY - should be after FROM ! If StringInStr($stempSQL, "GROUP BY", 0, -1) > 0 Then If StringInStr($stempSQL, "GROUP BY", 0, -1) > StringInStr($stempSQL, "FROM", 0, -1) Then $sSQLPart4 = @CRLF & "GROUP BY" & @CRLF & @TAB & StringTrimLeft($stempSQL, StringInStr($stempSQL, "GROUP BY", 0, -1) + 8) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "GROUP BY", 0, -1) + 1), 2) EndIf EndIf ; WHERE - should be after FROM ! If StringInStr($stempSQL, "WHERE", 0, -1) > 0 Then If StringInStr($stempSQL, "WHERE", 0, -1) > StringInStr($stempSQL, "FROM", 0, -1) Then $sSQLPart3 = @CRLF & "WHERE" & @CRLF & @TAB & StringTrimLeft($stempSQL, StringInStr($stempSQL, "WHERE", 0, -1) + 5) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "WHERE", 0, -1) + 1), 2) EndIf EndIf ; INNER JOIN If StringInStr($stempSQL, "INNER JOIN", 0, -1) > 0 Then $stempSQL = StringReplace($stempSQL, "INNER JOIN", @CRLF & @TAB & @TAB & "INNER JOIN") EndIf ; FROM If StringInStr($stempSQL, "FROM", 0, -1) > 0 Then $sSQLPart2 = @CRLF & "FROM" & @CRLF & @TAB & StringTrimLeft($stempSQL, StringInStr($stempSQL, "FROM", 0, -1) + 4) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "FROM", 0, -1) + 1), 2) EndIf ; SELECT If StringInStr($stempSQL, "SELECT", 0, 1) > 0 Then $sSQLPart1 = "SELECT" & @CRLF & @TAB & StringReplace(StringReplace(StringTrimLeft($stempSQL, StringInStr($stempSQL, "SELECT", 0, 1) + 6),", ", ",") , ",", "," & @CRLF & @TAB) $stempSQL = StringStripWS(StringTrimRight($stempSQL, StringLen($stempSQL) - StringInStr($stempSQL, "SELECT", 0, 1) + 1), 2) EndIf GUICtrlSetData ( $hConnString, $sConnectionString) GUICtrlSetData ( $ViewSQL, $sSQLPart1 & $sSQLPart2 & $sSQLPart3 & $sSQLPart4 & $sSQLPart5 & $sSQLPart6 & @CRLF ) EndFunc ;==>Format_SQL Script and database packs SQL demo DSN-less connections (multi-DB).zip GreenCan1 point
-
I wanted to make an analogue of Scanner It is necessary to drag and drop a folder in the window AutoIt v3.3.8.1 ; попытка идеального распределения #include <GUIConstantsEx.au3> #include <StaticConstants.au3> Global $Stack[50], $Stack1[50], $a, $a1, $BL, $List='', $k ;, $a1[600][2] GUICreate("Графический просмотр каталога", 380, 410, -1, -1, -1, 0x00000010) $StatusBar = GUICtrlCreateLabel('Строка состояния AZJIO 2010.06.16', 5, 415 - 20, 370, 15, $SS_LEFTNOWORDWRAP) $CatchDrop = GUICtrlCreateLabel(" кинь сюда каталог", 0, 0, 380, 17, $SS_SUNKEN) GUICtrlSetState(-1, 8) $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) $BL=GUICtrlCreateButton ("L", 360 ,24,18,18) GUICtrlSetTip(-1, 'список файлов') $RE=GUICtrlCreateButton ("R", 340 ,24,18,18) GUICtrlSetTip(-1, 'Перезапуск утилиты') GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = -13 If StringInStr(FileGetAttrib(@GUI_DragFile), "D") = 0 Then MsgBox(0, "Мелкая ошибка", 'Перетаскивайте каталог, а не файл.') ContinueLoop Else GUICtrlDelete($CatchDrop1) ;GUICtrlDelete($BL) GUICtrlDelete($a) GUICtrlDelete($a1) _Create() EndIf If $k = 0 Then $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) EndIf Case $msg = $RE _restart() Case $msg = $BL If $k <50 Then MsgBox(0, 'Список файлов', $List) Else If MsgBox(4, 'Список файлов', 'Слишком много, более 50,'&@CRLF&' хотите отправить список в буфер?')=6 Then ClipPut($List) EndIf Case $msg = -3 Exit EndSelect WEnd Func _Create() GUICtrlSetData($CatchDrop, @GUI_DragFile) FileFindNextFirst(@GUI_DragFile) $SizeTot=DirGetSize(@GUI_DragFile,2) ; размер каталога, подсчёт общего размера файлов $SizeMin = $SizeTot / 360 ; определяем минимальный размер отображаемого файла, не меньше градуса, количество байт приходящихся на один градус $Zdiff=0 ;создание графика $nach = 0 $List='' $k=0 $kT=0 $SizeTmp0=0 ;$SizeTotal=0 $a = GUICtrlCreateGraphic(10, 20, 360, 360) While 1 $tempname = FileFindNext('', 0, 1) If $tempname = "" Then ExitLoop $List&=StringRegExpReplace($tempname, '(^.*)\\(.*)$', '\2')&@CRLF $SizeTmp= FileGetSize($tempname) $kT+=1 ;$SizeTotal+=$SizeTmp If $SizeTmp<$SizeMin Then $SizeTmp0+=$SizeTmp ContinueLoop EndIf $Zdiff+=Mod($SizeTmp,$SizeMin) ; складываем остатки от деления в общую сумму If $Zdiff/$SizeMin >= 1 Then $Zdiff-=$SizeMin $SizeTmp+=$SizeMin EndIf $grad=Int($SizeTmp/$SizeMin) ; размер файла в градусах, угол файла (ширина сектора) $k+=1 GUICtrlSetGraphic($a, $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a, $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора ; $a1[$k][0] = GUICtrlCreateContextMenu($a) ; $a1[$k][1] = GUICtrlCreateMenuitem($tempname,$a1[$k][0]) ;MsgBox(0, 'ага', $nach&' начало сектора' &@CRLF& $grad& ' - размер сектора') ; попытка создать лейблы имён файлов ; If $k<7 Then ; GUICtrlCreateLabel($k, (90+$k*14)*cos($nach)+190, (90+$k*14)*sin($nach)+200, 10, 14) ; GUICtrlSetTip(-1, $tempname) ; EndIf $nach += $grad ; начальный угол отсчёта (смещение, сдвиг) WEnd GUICtrlSetState($a, 8) If $k = 0 Then Return $k ; жёлтый участок, размер этих файлов не позволяет задать угол в круговой диаграмме, так как он менее градуса. $grad=Int($SizeTmp0/$SizeMin) $k+=1 If $nach+$grad >= 359 Then $grad+=360-$nach-$grad GUICtrlSetGraphic($a, $GUI_GR_COLOR, 0, 0xe9de12) ; цвет сектора, жёлтый GUICtrlSetGraphic($a, $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора GUICtrlSetState(-1, 8) ;$nach += $grad ;Круг по центру $a1 = GUICtrlCreateGraphic(10, 20, 360, 360) ;GUICtrlSetGraphic($a1, $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a1, $GUI_GR_COLOR, 0, 0xe0dfe3) GUICtrlSetGraphic($a1, $GUI_GR_ELLIPSE, 135, 135, 90, 90) GUICtrlSetGraphic($a1, $GUI_GR_REFRESH) ;MsgBox(0, 'Сообщение', $nach) ;MsgBox(0, 'ага', $SizeTot&' размер в байтах' &@CRLF& $SizeTot/1024/1024& ' - размер в мегабайтах'&@CRLF& $SizeTotal& ' - размер в байтах по файлам'&@CRLF& $SizeTotal/1024/1024& ' - размер в мегабайтах по файлам') GUICtrlSetData($StatusBar, 'Размер ' & Round($SizeTot / 1024 / 1024,1) & ' Мб колич ' & $kT & ' путь ' & @GUI_DragFile) If $k <50 Then GUICtrlSetTip($CatchDrop,$List) Else GUICtrlSetTip($CatchDrop,'Слишком много файлов, более 50') EndIf EndFunc ;==>_Create ;======================================== ; функция поиска всех файлов в каталоге (NIKZZZZ+мод_AZJIO) Func FileFindNextFirst($FindCat) $Stack[0] = 1 $Stack1[1] = $FindCat $Stack[1] = FileFindFirstFile($FindCat & "\*.*") Return $Stack[1] EndFunc ;==>FileFindNextFirst Func FileFindNext($type = 'log', $mode = 0, $Level = 49) While 1 $file = FileFindNextFile($Stack[$Stack[0]]) If @error Then FileClose($Stack[$Stack[0]]) If $Stack[0] = 1 Then Return "" Else $Stack[0] -= 1 ContinueLoop EndIf Else If StringInStr(FileGetAttrib($Stack1[$Stack[0]] & "\" & $file), "D") > 0 Then If $Stack[0] = $Level Then ContinueLoop $Stack[0] += 1 $Stack1[$Stack[0]] = $Stack1[$Stack[0] - 1] & "\" & $file $Stack[$Stack[0]] = FileFindFirstFile($Stack1[$Stack[0]] & "\*.*") If $mode = 2 Then Return $Stack1[$Stack[0]] Else ContinueLoop EndIf Else If $mode = 2 Then ContinueLoop If $mode = 1 Then If StringInStr(';' & $type & ';', ';' & StringRight($Stack1[$Stack[0]] & "\" & $file, 3) & ';') = 0 Then ContinueLoop Else Return $Stack1[$Stack[0]] & "\" & $file EndIf Else Return $Stack1[$Stack[0]] & "\" & $file EndIf EndIf EndIf WEnd EndFunc ;==>FileFindNext Func _restart() Local $sAutoIt_File = @TempDir & "\~Au3_ScriptRestart_TempFile.au3" Local $sRunLine, $sScript_Content, $hFile $sRunLine = @ScriptFullPath If Not @Compiled Then $sRunLine = @AutoItExe & ' /AutoIt3ExecuteScript ""' & $sRunLine & '""' If $CmdLine[0] > 0 Then $sRunLine &= ' ' & $CmdLineRaw $sScript_Content &= '#NoTrayIcon' & @CRLF & _ 'While ProcessExists(' & @AutoItPID & ')' & @CRLF & _ ' Sleep(10)' & @CRLF & _ 'WEnd' & @CRLF & _ 'Run("' & $sRunLine & '")' & @CRLF & _ 'FileDelete(@ScriptFullPath)' & @CRLF $hFile = FileOpen($sAutoIt_File, 2) FileWrite($hFile, $sScript_Content) FileClose($hFile) Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & $sAutoIt_File & '"', @ScriptDir, @SW_HIDE) Sleep(1000) Exit EndFunc ;==>_restart +GUICtrlCreateLabel ; попытка идеального распределения #include <GUIConstantsEx.au3> #include <StaticConstants.au3> Global $Stack[50], $Stack1[50], $a, $a1, $BL, $List='', $k, $aLab, $y[20] =['','','','','','','','','','','','','','','','','','','',''] GUICreate("Графический просмотр каталога", 380, 410, -1, -1, -1, 0x00000010) $StatusBar = GUICtrlCreateLabel('Строка состояния AZJIO 2010.06.16', 5, 415 - 20, 370, 15, $SS_LEFTNOWORDWRAP) $CatchDrop = GUICtrlCreateLabel(" кинь сюда каталог", 0, 0, 380, 17, $SS_SUNKEN) GUICtrlSetState(-1, 8) $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) $BL=GUICtrlCreateButton ("L", 360 ,24,18,18) GUICtrlSetTip(-1, 'Список крупных файлов') $RE=GUICtrlCreateButton ("R", 340 ,24,18,18) GUICtrlSetTip(-1, 'Перезапуск утилиты') GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = -13 If StringInStr(FileGetAttrib(@GUI_DragFile), "D") = 0 Then MsgBox(0, "Мелкая ошибка", 'Перетаскивайте каталог, а не файл.') ContinueLoop Else GUICtrlDelete($CatchDrop1) ; GUICtrlDelete($BL) For $i = 1 to 19 If $y[$i] <>'' Then GUICtrlDelete($y[$i]) Next GUICtrlDelete($a) GUICtrlDelete($a1) _Create() EndIf If $k = 0 Then $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) EndIf Case $msg = $RE _restart() Case $msg = $BL MsgBox(0, 'Список крупных файлов', $List) ; If $k <50 Then ; MsgBox(0, 'Список крупных файлов', $List) ; Else ; If MsgBox(4, 'Список файлов', 'Слишком много, более 50,'&@CRLF&' хотите отправить список в буфер?')=6 Then ClipPut($List) ; EndIf Case $msg = -3 Exit EndSelect WEnd Func _Create() GUICtrlSetData($CatchDrop, @GUI_DragFile) FileFindNextFirst(@GUI_DragFile) $SizeTot=DirGetSize(@GUI_DragFile,2) ; размер каталога, подсчёт общего размера файлов $SizeMin = $SizeTot / 360 ; определяем минимальный размер отображаемого файла, не меньше градуса, количество байт приходящихся на один градус $Zdiff=0 ;создание графика $nach = 0 $List='' $k=0 $kT=0 $SizeTmp0=0 $Lab='' ;$SizeTotal=0 $a = GUICtrlCreateGraphic(10, 20, 360, 360) While 1 $tempname = FileFindNext('', 0, 1) If $tempname = "" Then ExitLoop ;$List&=StringRegExpReplace($tempname, '(^.*)\\(.*)$', '\2')&@CRLF $SizeTmp= FileGetSize($tempname) $kT+=1 ;$SizeTotal+=$SizeTmp If $SizeTmp<$SizeMin Then $SizeTmp0+=$SizeTmp ContinueLoop EndIf $Zdiff+=Mod($SizeTmp,$SizeMin) ; складываем остатки от деления в общую сумму If $Zdiff/$SizeMin >= 1 Then $Zdiff-=$SizeMin $SizeTmp+=$SizeMin EndIf $grad=Int($SizeTmp/$SizeMin) ; размер файла в градусах, угол файла (ширина сектора) $k+=1 GUICtrlSetGraphic($a, $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a, $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора ;MsgBox(0, 'ага', $nach&' начало сектора' &@CRLF& $grad& ' - размер сектора') ; попытка создать лейблы имён файлов $rp=($nach+$grad/2)*0.0174532925199433 If $grad>10 Then $Lab&='|'&170*cos(-$rp)+185&'|'&170*sin(-$rp)+195&'|'&$tempname ;If $grad>20 Then MsgBox(0, 'Сообщение', $nach+$grad/2&@CRLF&cos($rp)&' - cos'&@CRLF&sin($rp)&' - sin') $nach += $grad ; начальный угол отсчёта (смещение, сдвиг) WEnd GUICtrlSetState($a, 8) If $k = 0 Then Return $k ; жёлтый участок, размер этих файлов не позволяет задать угол в круговой диаграмме, так как он менее градуса. $grad=Int($SizeTmp0/$SizeMin) $k+=1 If $nach+$grad >= 359 Then $grad+=360-$nach-$grad GUICtrlSetGraphic($a, $GUI_GR_COLOR, 0, 0xe9de12) ; цвет сектора, жёлтый GUICtrlSetGraphic($a, $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора GUICtrlSetState(-1, 8) ;$nach += $grad ;Круг по центру $a1 = GUICtrlCreateGraphic(10, 20, 360, 360) ;GUICtrlSetGraphic($a1, $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a1, $GUI_GR_COLOR, 0, 0xe0dfe3) GUICtrlSetGraphic($a1, $GUI_GR_ELLIPSE, 135, 135, 90, 90) GUICtrlSetGraphic($a1, $GUI_GR_REFRESH) $aLab=StringSplit(StringTrimLeft($Lab, 1), '|') $rt=0 For $i = 1 to $aLab[0] Step 3 $rt+=1 $y[$rt]=GUICtrlCreateLabel($rt,$aLab[$i], $aLab[$i+1], 12, 14) ;Sleep(30) GUICtrlSetTip(-1, $aLab[$i+2]) ; $context = GUICtrlCreateContextMenu(-1) ; GUICtrlCreateMenuitem($aLab[$i+2],$context) $List&=$rt&') '&StringRegExpReplace($aLab[$i+2], '(^.*)\\(.*)$', '\2')&@CRLF ;MsgBox(0, 'Сообщение', $y[$rt]&' - ID'&@CRLF&$rt&' - №'&@CRLF&$aLab[$i]&' - слева'&@CRLF&$aLab[$i+1]&' - сверху'&@CRLF&$aLab[$i+2]) Next ;MsgBox(0, 'Сообщение', $nach) ;MsgBox(0, 'ага', $SizeTot&' размер в байтах' &@CRLF& $SizeTot/1024/1024& ' - размер в мегабайтах'&@CRLF& $SizeTotal& ' - размер в байтах по файлам'&@CRLF& $SizeTotal/1024/1024& ' - размер в мегабайтах по файлам') GUICtrlSetData($StatusBar, 'Размер ' & Round($SizeTot / 1024 / 1024,1) & ' Мб колич ' & $kT & ' путь ' & @GUI_DragFile) If $k <50 Then GUICtrlSetTip($CatchDrop,$List) Else GUICtrlSetTip($CatchDrop,'Слишком много файлов, более 50') EndIf EndFunc ;==>_Create ;======================================== ; функция поиска всех файлов в каталоге (NIKZZZZ+мод_AZJIO) Func FileFindNextFirst($FindCat) $Stack[0] = 1 $Stack1[1] = $FindCat $Stack[1] = FileFindFirstFile($FindCat & "\*.*") Return $Stack[1] EndFunc ;==>FileFindNextFirst Func FileFindNext($type = 'log', $mode = 0, $Level = 49) While 1 $file = FileFindNextFile($Stack[$Stack[0]]) If @error Then FileClose($Stack[$Stack[0]]) If $Stack[0] = 1 Then Return "" Else $Stack[0] -= 1 ContinueLoop EndIf Else If StringInStr(FileGetAttrib($Stack1[$Stack[0]] & "\" & $file), "D") > 0 Then If $Stack[0] = $Level Then ContinueLoop $Stack[0] += 1 $Stack1[$Stack[0]] = $Stack1[$Stack[0] - 1] & "\" & $file $Stack[$Stack[0]] = FileFindFirstFile($Stack1[$Stack[0]] & "\*.*") If $mode = 2 Then Return $Stack1[$Stack[0]] Else ContinueLoop EndIf Else If $mode = 2 Then ContinueLoop If $mode = 1 Then If StringInStr(';' & $type & ';', ';' & StringRight($Stack1[$Stack[0]] & "\" & $file, 3) & ';') = 0 Then ContinueLoop Else Return $Stack1[$Stack[0]] & "\" & $file EndIf Else Return $Stack1[$Stack[0]] & "\" & $file EndIf EndIf EndIf WEnd EndFunc ;==>FileFindNext Func _restart() Local $sAutoIt_File = @TempDir & "\~Au3_ScriptRestart_TempFile.au3" Local $sRunLine, $sScript_Content, $hFile $sRunLine = @ScriptFullPath If Not @Compiled Then $sRunLine = @AutoItExe & ' /AutoIt3ExecuteScript ""' & $sRunLine & '""' If $CmdLine[0] > 0 Then $sRunLine &= ' ' & $CmdLineRaw $sScript_Content &= '#NoTrayIcon' & @CRLF & _ 'While ProcessExists(' & @AutoItPID & ')' & @CRLF & _ ' Sleep(10)' & @CRLF & _ 'WEnd' & @CRLF & _ 'Run("' & $sRunLine & '")' & @CRLF & _ 'FileDelete(@ScriptFullPath)' & @CRLF $hFile = FileOpen($sAutoIt_File, 2) FileWrite($hFile, $sScript_Content) FileClose($hFile) Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & $sAutoIt_File & '"', @ScriptDir, @SW_HIDE) Sleep(1000) Exit EndFunc ;==>_restart . ; попытка идеального распределения #include <GUIConstantsEx.au3> #include <StaticConstants.au3> Global $Stack[50], $Stack1[50], $a[600], $BL, $List='', $k ;, $a1[600][2] GUICreate("Графический просмотр каталога", 380, 410, -1, -1, -1, 0x00000010) $StatusBar = GUICtrlCreateLabel('Строка состояния AZJIO 2010.06.16', 5, 415 - 20, 370, 15, $SS_LEFTNOWORDWRAP) $CatchDrop = GUICtrlCreateLabel(" кинь сюда каталог", 0, 0, 380, 17, $SS_SUNKEN) GUICtrlSetState(-1, 8) $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) $BL=GUICtrlCreateButton ("L", 360 ,24,18,18) GUICtrlSetTip(-1, 'список файлов') $RE=GUICtrlCreateButton ("R", 340 ,24,18,18) GUICtrlSetTip(-1, 'Перезапуск утилиты') GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = -13 If StringInStr(FileGetAttrib(@GUI_DragFile), "D") = 0 Then MsgBox(0, "Мелкая ошибка", 'Перетаскивайте каталог, а не файл.') ContinueLoop Else GUICtrlDelete($CatchDrop1) ;GUICtrlDelete($BL) For $i = 1 to $k+1 GUICtrlDelete($a[$i]) Next GUICtrlDelete($a) _Create() EndIf If $k = 0 Then $CatchDrop1 = GUICtrlCreateLabel("", 0, 20, 380, 360) GUICtrlSetState(-1, 136) EndIf Case $msg = $RE _restart() Case $msg = $BL If $k <50 Then MsgBox(0, 'Список файлов', $List) Else If MsgBox(4, 'Список файлов', 'Слишком много, более 50,'&@CRLF&' хотите отправить список в буфер?')=6 Then ClipPut($List) EndIf Case $msg = -3 Exit EndSelect WEnd Func _Create() GUICtrlSetData($CatchDrop, @GUI_DragFile) FileFindNextFirst(@GUI_DragFile) $SizeTot=DirGetSize(@GUI_DragFile,2) ; размер каталога, подсчёт общего размера файлов $SizeMin = $SizeTot / 360 ; определяем минимальный размер отображаемого файла, не меньше градуса, количество байт приходящихся на один градус $Zdiff=0 ;создание графика $nach = 0 $List='' $k=0 $kT=0 $SizeTmp0=0 ;$SizeTotal=0 While 1 $tempname = FileFindNext('', 0, 1) If $tempname = "" Then ExitLoop $List&=StringRegExpReplace($tempname, '(^.*)\\(.*)$', '\2')&@CRLF $SizeTmp= FileGetSize($tempname) $kT+=1 ;$SizeTotal+=$SizeTmp If $SizeTmp<$SizeMin Then $SizeTmp0+=$SizeTmp ContinueLoop EndIf $Zdiff+=Mod($SizeTmp,$SizeMin) ; складываем остатки от деления в общую сумму If $Zdiff/$SizeMin >= 1 Then $Zdiff-=$SizeMin $SizeTmp+=$SizeMin EndIf $grad=Int($SizeTmp/$SizeMin) ; размер файла в градусах, угол файла (ширина сектора) $k+=1 $a[$k] = GUICtrlCreateGraphic(10, 20, 360, 360) GUICtrlSetGraphic($a[$k], $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a[$k], $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора GUICtrlSetState(-1, 8) ; $a1[$k][0] = GUICtrlCreateContextMenu($a[$k]) ; $a1[$k][1] = GUICtrlCreateMenuitem($tempname,$a1[$k][0]) ;MsgBox(0, 'ага', $nach&' начало сектора' &@CRLF& $grad& ' - размер сектора') ; попытка создать лейблы имён файлов ; If $k<7 Then ; GUICtrlCreateLabel($k, (90+$k*14)*cos($nach)+190, (90+$k*14)*sin($nach)+200, 10, 14) ; GUICtrlSetTip(-1, $tempname) ; EndIf $nach += $grad ; начальный угол отсчёта (смещение, сдвиг) WEnd If $k = 0 Then Return $k ; жёлтый участок, размер этих файлов не позволяет задать угол в круговой диаграмме, так как он менее градуса. $grad=Int($SizeTmp0/$SizeMin) $k+=1 If $nach+$grad >= 359 Then $grad+=360-$nach-$grad $a[$k] = GUICtrlCreateGraphic(10, 20, 360, 360) GUICtrlSetGraphic($a[$k], $GUI_GR_COLOR, 0, 0xe9de12) ; цвет сектора, жёлтый GUICtrlSetGraphic($a[$k], $GUI_GR_PIE, 180, 180, 180, $nach, $grad) ; создание сектора GUICtrlSetState(-1, 8) ;$nach += $grad ;Круг по центру $a[$k+1] = GUICtrlCreateGraphic(10, 20, 360, 360) ;GUICtrlSetGraphic($a[$k+1], $GUI_GR_COLOR, 0, Dec(Random(50, 99, 1) & Random(50, 99, 1) & Random(50, 99, 1))) ; цвет сектора, рандомный GUICtrlSetGraphic($a[$k+1], $GUI_GR_COLOR, 0, 0xe0dfe3) GUICtrlSetGraphic($a[$k+1], $GUI_GR_ELLIPSE, 135, 135, 90, 90) GUICtrlSetGraphic($a[$k+1], $GUI_GR_REFRESH) ;MsgBox(0, 'Сообщение', $nach) ;MsgBox(0, 'ага', $SizeTot&' размер в байтах' &@CRLF& $SizeTot/1024/1024& ' - размер в мегабайтах'&@CRLF& $SizeTotal& ' - размер в байтах по файлам'&@CRLF& $SizeTotal/1024/1024& ' - размер в мегабайтах по файлам') GUICtrlSetData($StatusBar, 'Размер ' & Round($SizeTot / 1024 / 1024,1) & ' Мб колич ' & $kT & ' путь ' & @GUI_DragFile) If $k <50 Then GUICtrlSetTip($CatchDrop,$List) Else GUICtrlSetTip($CatchDrop,'Слишком много файлов, более 50') EndIf EndFunc ;==>_Create ;======================================== ; функция поиска всех файлов в каталоге (NIKZZZZ+мод_AZJIO) Func FileFindNextFirst($FindCat) $Stack[0] = 1 $Stack1[1] = $FindCat $Stack[1] = FileFindFirstFile($FindCat & "\*.*") Return $Stack[1] EndFunc ;==>FileFindNextFirst Func FileFindNext($type = 'log', $mode = 0, $Level = 49) While 1 $file = FileFindNextFile($Stack[$Stack[0]]) If @error Then FileClose($Stack[$Stack[0]]) If $Stack[0] = 1 Then Return "" Else $Stack[0] -= 1 ContinueLoop EndIf Else If StringInStr(FileGetAttrib($Stack1[$Stack[0]] & "\" & $file), "D") > 0 Then If $Stack[0] = $Level Then ContinueLoop $Stack[0] += 1 $Stack1[$Stack[0]] = $Stack1[$Stack[0] - 1] & "\" & $file $Stack[$Stack[0]] = FileFindFirstFile($Stack1[$Stack[0]] & "\*.*") If $mode = 2 Then Return $Stack1[$Stack[0]] Else ContinueLoop EndIf Else If $mode = 2 Then ContinueLoop If $mode = 1 Then If StringInStr(';' & $type & ';', ';' & StringRight($Stack1[$Stack[0]] & "\" & $file, 3) & ';') = 0 Then ContinueLoop Else Return $Stack1[$Stack[0]] & "\" & $file EndIf Else Return $Stack1[$Stack[0]] & "\" & $file EndIf EndIf EndIf WEnd EndFunc ;==>FileFindNext Func _restart() Local $sAutoIt_File = @TempDir & "\~Au3_ScriptRestart_TempFile.au3" Local $sRunLine, $sScript_Content, $hFile $sRunLine = @ScriptFullPath If Not @Compiled Then $sRunLine = @AutoItExe & ' /AutoIt3ExecuteScript ""' & $sRunLine & '""' If $CmdLine[0] > 0 Then $sRunLine &= ' ' & $CmdLineRaw $sScript_Content &= '#NoTrayIcon' & @CRLF & _ 'While ProcessExists(' & @AutoItPID & ')' & @CRLF & _ ' Sleep(10)' & @CRLF & _ 'WEnd' & @CRLF & _ 'Run("' & $sRunLine & '")' & @CRLF & _ 'FileDelete(@ScriptFullPath)' & @CRLF $hFile = FileOpen($sAutoIt_File, 2) FileWrite($hFile, $sScript_Content) FileClose($hFile) Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & $sAutoIt_File & '"', @ScriptDir, @SW_HIDE) Sleep(1000) Exit EndFunc ;==>_restart .1 point
-
Or this, without include $path = "C:\Users\profilename" msgbox(0,"", DllCall('shlwapi.dll', 'bool', 'PathRemoveFileSpecW', 'wstr', $path)[1])1 point
-
david1337, Not that hard to do: #include <GUIConstantsEx.au3> #include <ButtonConstants.au3> #include <WinAPI.au3> Global $aButton[9] Mainscript() Func Mainscript() GUICreate("", 1265, 625) ; will create a dialog box that when displayed is centered Opt("GUICoordMode", 4) ; Get the button controlIDs into an array $aButton[1] = GUICtrlCreateButton("Button 1", 50, 30, 262, 262) $aButton[2] = GUICtrlCreateButton("Button 2", 350, 30, 262, 262) $aButton[3] = GUICtrlCreateButton("Button 3", 650, 30, 262, 262) $aButton[4] = GUICtrlCreateButton("Button 4", 950, 30, 262, 262) $aButton[5] = GUICtrlCreateButton("Button 5", 50, 330, 262, 262) $aButton[6] = GUICtrlCreateButton("Button 6", 350, 330, 262, 262) $aButton[7] = GUICtrlCreateButton("Button 7", 650, 330, 262, 262) $aButton[8] = GUICtrlCreateButton("Button 8", 950, 330, 262, 262) $cDummy_Up = GUICtrlCreateDummy() $cDummy_Dn = GUICtrlCreateDummy() GUISetState() GUICtrlSetState($aButton[1], $GUI_FOCUS) ; Set the Up/Down keys as accelerators - they will only act like this when your GUI is active Local $aAccelKeys[2][2] = [["{UP}", $cDummy_Up], ["{DOWN}", $cDummy_Dn]] GUISetAccelerators($aAccelKeys) While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $cDummy_Up _Vertical_TabStop() Case $msg = $cDummy_Dn _Vertical_TabStop() EndSelect WEnd #cs ; Perhaps easier to use a Switch structure: While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop Case $cDummy_Up, $cDummy_Dn _Vertical_TabStop() EndSwitch WEnd #ce EndFunc ;==>Mainscript Func _Vertical_TabStop() ; Get active control $hActive = _WinAPI_GetFocus() For $i = 1 To 8 ; If it is a button If $hActive = GUICtrlGetHandle($aButton[$i]) Then ; Then determine index of the button above/below $iIndex = Mod($i + 4, 8) ; This is the magic bit <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ; and set focus GUICtrlSetState($aButton[$iIndex], $GUI_FOCUS) ; No point in looking further ExitLoop EndIf Next EndFunc Please ask if you have any questions. M231 point
-
david1337, Perhaps you could use background labels like this: #include <GUIConstantsEx.au3> #include <ButtonConstants.au3> #include <WinAPI.au3> Mainscript() Func Mainscript() Local $Button_1, $Button_2, $msg GUICreate("", 634, 320) ; will create a dialog box that when displayed is centered Opt("GUICoordMode", 4) $cLabel_1 = GUICtrlCreateLabel("", 18, 25, 272, 272) GUICtrlSetBkColor($cLabel_1, 0x00FF00) GUICtrlSetState($cLabel_1, $GUI_DISABLE) $Button_1 = GUICtrlCreateButton("Button 1", 23, 30, 262, 262, $BS_BITMAP) $cLabel_2 = GUICtrlCreateLabel("", 345, 25, 272, 272) GUICtrlSetBkColor($cLabel_2, 0xFF0000) GUICtrlSetState($cLabel_2, $GUI_DISABLE) $Button_2 = GUICtrlCreateButton("Button 2", 350, 30, 262, 262, $BS_BITMAP) GUISetBkColor(0xFFFFFF) GUISetState() GUICtrlSetState($Button_1, $GUI_FOCUS) $hActive = GUICtrlGetHandle($Button_1) ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $Button_1 MsgBox(0,"","Button 1") Case $msg = $Button_2 MsgBox(0,"","Button 2") EndSelect $hCurrFocus = _WinAPI_GetFocus() If $hCurrFocus <> $hActive Then $hActive = $hCurrFocus Switch $hActive Case GUICtrlGetHandle($Button_1) GUICtrlSetBkColor($cLabel_1, 0x00FF00) GUICtrlSetBkColor($cLabel_2, 0xFF0000) Case GUICtrlGetHandle($Button_2) GUICtrlSetBkColor($cLabel_2, 0x00FF00) GUICtrlSetBkColor($cLabel_1, 0xFF0000) EndSwitch EndIf WEnd EndFunc ;==>Mainscript M231 point
-
Vmware + autoit
benny12 reacted to argumentum for a topic
hope this helps Local $a = VmwareInventoryToArray() #include <Array.au3> ; ..just to show the array _ArrayDisplay($a, "from VmwareInventoryToArray()") ; ..just to show the array Func VmwareInventoryToArray() Local $a[1][2] $a[0][0] = 0 Local $sFile = FileRead(@UserProfileDir & "\AppData\Roaming\VMware\inventory.vmls") If $sFile = "" Then Return SetError(1, 1, $a) Local $n, $p, $aFile = StringSplit($sFile, @CRLF) Local $a[14][1000] $a[0][0] = 0 $a[1][0] = "SelfIndex" For $n = 1 To $aFile[0] If StringLeft($aFile[$n], 6) = "vmlist" Then Switch StringMid($aFile[$n], StringInStr($aFile[$n], '.') + 1, StringInStr($aFile[$n], '=') - StringInStr($aFile[$n], '.') - 2) Case "config" $p = VmwareInventoryToArray_AddToArray($a, $aFile[$n], 2) VmwareInventoryToArray_AddToArray_ISOfile($a, $p, 13) Case "DisplayName" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 3) Case "ParentID" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 4) Case "ItemID" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 5) Case "SeqID" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 6) Case "IsFavorite" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 7) Case "IsClone" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 8) Case "CfgVersion" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 9) Case "State" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 10) Case "UUID" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 11) Case "IsCfgPathNormalized" VmwareInventoryToArray_AddToArray($a, $aFile[$n], 12) EndSwitch EndIf Next ReDim $a[14][$a[0][0] + 1] If $a[0][0] > 990 Then $a[0][1] = "you've got too many entries !" Return SetError(2, 1, $a) ; something is very wrong if you have over 100 VMs on 1 PC EndIf $a[0][1] = "OK" Return SetError(0, 0, $a) EndFunc ;==>VmwareInventoryToArray Func VmwareInventoryToArray_AddToArray_ISOfile(ByRef $a, $p, $i) If Not $p Then Return Local $sFile = FileRead($a[2][$p]) If $sFile = "" Then Return If $a[$i][0] = "" Then $a[$i][0] = "ISO file" Local $aFile = StringSplit($sFile, @CRLF) For $n = 1 To $aFile[0] If StringRight($aFile[$n], 5) = '.iso"' Then $a[$i][$p] = StringTrimRight(StringTrimLeft($aFile[$n], StringInStr($aFile[$n], '=') + 2), 1) Return EndIf Next EndFunc ;==>VmwareInventoryToArray_AddToArray_ISOfile Func VmwareInventoryToArray_GetArrayPos($i, ByRef $a) Local $n $i = Int($i) For $n = 999 To 1 Step -1 If $a[1][$n] = $i Then Return $n Next For $n = 1 To 999 Step 1 If $a[1][$n] = "" Then $a[1][$n] = $i $a[0][0] = $a[0][0] + 1 Return $n EndIf Next Return 999 EndFunc ;==>VmwareInventoryToArray_GetArrayPos Func VmwareInventoryToArray_AddToArray(ByRef $a, $s, $i) If $a[$i][0] = "" Then $a[$i][0] = StringMid($s, StringInStr($s, '.') + 1, StringInStr($s, '=') - StringInStr($s, '.') - 2) If StringTrimRight(StringTrimLeft($s, StringInStr($s, '=') + 2), 1) = "" Then Return 0 Local $p = VmwareInventoryToArray_GetArrayPos(Int(StringMid($s, 7, StringInStr($s, '.') - 7)), $a) $a[$i][$p] = StringTrimRight(StringTrimLeft($s, StringInStr($s, '=') + 2), 1) Return $p EndFunc ;==>VmwareInventoryToArray_AddToArray Edit: added to know what CD it used from the VMX file, you don't need it but I wanted to.1 point -
Any other method besides Shell.Windows for creating _IEAttach browser object?
MuffinMan reacted to JLogan3o13 for a topic
Can you please clarify your methodology? You want to run the IE instance as a published app, and use an AutoIt script to do an IEAttach from the client desktop - is that correct? Depending on how the app is being published, this may be problematic at best. Whether you're doing it through Citrix or VMWare, the whole point of publishing applications is encapsulation. If your script sits outside the virtualization "bubble" it is going to be nigh impossible to attach to it. If you're talking about embedding both AutoIt and IE into the published app, however, that is another matter.1 point -
Make the parent GUI be the GUI with the button, and have a child GUI that will always open. Have a look at this tutorial: Managing Multiple GUIs P.S. Here is an example of how you would keep one variable the same and keep the main GUI on top, and up at the same time as the child. #include <GUIConstants.au3> ; variable declarations Global $pGUI, $cGUI, $msg, $iStored = 0, $pButton, $cButton = 9999, $input ; function call MainGUI() ; main msg event loop While 1 $msg = GUIGetMsg(1) Switch $msg[1] Case $pGUI Switch $msg[0] Case $GUI_EVENT_CLOSE Exit Case $pButton ChildGUI() EndSwitch Case $cGUI Switch $msg[0] Case $GUI_EVENT_CLOSE GUIDelete($cGUI) Case $cButton $iStored += 1 GUICtrlSetData($input, $iStored) EndSwitch EndSwitch WEnd ; main gui function Func MainGUI() $pGUI = GUICreate("MAIN GUI", 100, 80, -1, -1, $WS_SIZEBOX, $WS_EX_TOPMOST) WinMove("MAIN GUI", "", 0, 0) $pButton = GUICtrlCreateButton("Click Me", 15, 15) GUISetState(@SW_SHOW) EndFunc ;==>MainGUI ; main child gui function Func ChildGUI() $cGUI = GUICreate("CHILD GUI", 150, 125, -1, -1, $WS_SIZEBOX) $cButton = GUICtrlCreateButton("Add 1", 5, 15) $input = GUICtrlCreateInput($iStored, 50, 15, 30, 15, $ES_READONLY) GUICtrlCreateLabel("if you close this, the" & @CRLF & "input will be the same.", 5, 50) GUISetState(@SW_SHOW) EndFunc Any questions?1 point
-
I used to use Visual Studio 6 (yeah, right, that pre-2000 one) as well as applications made using this. Now, applications using VS6 APIs, or really any older API such as DirectX (Direct3D & DirectSound), older CommonControls etc. were supported all the way up to Windows 7. Windows 8(.1) has little to no support for any of those. Partially, this could be bypassed by using XP-Mode. I'm happy to say that Windows 10 (Build >9841, Up2Date 16/01/2015) again supports them all and more. This might be good news for fans of really old games or devs who just use older tools for fun Note: Support for older APIs has nothing to do with "Compatibility Mode". Edit (1): This might happened in response to this: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3440221-bring-back-classic-visual-basic-an-improved-versi1 point
-
Locking Computer
nirmalsalem reacted to JLogan3o13 for a topic
ShellExecute("rundll32.exe", 'user32.dll,LockWorkStation')1 point -
I'm experienced in both WinBatch and AutoIt . Honestly I can tell you the major difference between the two is with WinBatch is you have to pay for it and AutoIt is free. I've never found anything that WinBatch could do that AutoIt could not do. Saying that I've pretty much dropped WinBatch for AutoIt and never looked back. My experienced opinion is this: Use AutoIt in place of WinBatch and enjoy.1 point
-
This is the completed working code: #include <GUIConstantsEx.au3> #include <StaticConstants.au3> Global $sIni, $Dirs, $GUI Global $DefsetgFull, $DefSetgDir, $DefSetgPath, $DefSetgExcelCap Global $sFilePath1, $sFilePath2, $sFile Global $array1 ;Set ini file $sIni = @ScriptDir & "\InputBox.ini" _sIni() ;Read ini file _rIni() $GUI = GUICreate("InputBox", 350, 225) ; Create dialog box displayed center ; Main Label Title $lbl_txt1 = GUICtrlCreateLabel("InputBox example test!", 5, 10, 345, 15, $SS_CENTER) ; Open File Label $lbl_txt2 = GUICtrlCreateLabel("Select or Open File", 5, 75, 215, 25) ; Inputbox $ipt_1 = GuiCtrlCreateInput($DefSetgFull, 5, 100, 330, 16, -1) ; Buttons $btn_Select = GUICtrlCreateButton("Select", 185, 125, 75, 25) $btn_Open = GUICtrlCreateButton("Open", 261, 125, 75, 25) GUISetState() ; display dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $btn_Select ;Select File $sFile = FileOpenDialog("Select file:", $DefSetgFull, "All Files (*.*)") If @error Then ContinueLoop GUICtrlSetData($ipt_1, $sFile) ; GUI will be updated at next iteration IniWrite($sIni, "default", "setgfull", $sFile) ;Set selected file caption title $array1 = StringSplit($sFile, '\', 1) IniWrite($sIni, "default", "setgexcelcap", $array1[UBound($array1) -1] & " - Notepad2") ;Read ini file _rINI() MsgBox(0, "", "Select: " & $DefSetgFull) Case $msg = $btn_Open ;Open File MsgBox(1, "", StringLen($DefSetgExcelCap) & " -- " & $DefSetgExcelCap) If Not WinExists($DefSetgExcelCap) Then ;=MsgBox(1, "", $DefSetgExcelCap & " < Caption ---- Path > " & $sFilePath1) ;=MsgBox(1, "", $DefSetgFull & " < Default Full Path") MsgBox(0, "", "Open: " & $DefSetgFull) ShellExecute($DefSetgFull) EndIf EndSelect WEnd Func _exit() Exit EndFunc Func _sIni() ;Settings for ini file $Dirs = "DirAppDataCom=" & @AppDataCommonDir & @LF & _ "DirAppDataDir=" & @AppDataDir & @LF & _ "DirComFiles=" & @CommonFilesDir & @LF & _ "DirDsktpCom=" & @DesktopCommonDir & @LF & _ "DirDsktp=" & @DesktopDir & @LF & _ "DirDocCom=" & @DocumentsCommonDir & @LF & _ "DirMyDoc=" & @MyDocumentsDir & @LF & _ "DirProFiles=" & @ProgramFilesDir & @LF & _ "DirProCom=" & @ProgramsCommonDir & @LF & _ "DirPro=" & @ProgramsDir & @LF & _ "DirSys=" & @SystemDir & @LF & _ "ScriptFullPath=" & @ScriptFullPath & @LF & _ "DirWin=" & @WindowsDir & @LF & _ "DirWrk=" & @WorkingDir & @LF & _ "CompName=" & @ComputerName & @LF IniWriteSection($sIni, "Dirs", $Dirs) EndFunc ;iniFile Func _rIni() ;Read ini file $DefSetgDir = IniRead($sIni, "Default", "setgdir", "NotFound") $DefSetgPath = IniRead($sIni, "Default", "setgpath", "NotFound") $DefSetgFull = IniRead($sIni, "Default", "setgfull", "NotFound") $DefSetgExcelCap = IniRead($sIni, "Default", "setgexcelcap", "NotFound") EndFunc jfcby1 point