[x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

Post your working scripts, libraries and tools
Guest_3102018a

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

10 Mar 2018, 15:26

I can't say. All I know is that I experience the same issue as tempuser. Sometimes the script works, sometimes it doesn't. Is it possible that both our issues stem from "OpenProcess" not working? Maybe, but it seems from the warning that iProcessID is blank, which results in OpenProcess not working. Having placed a Msgbox in the code, sometimes hwWindow is blank, which would make "WinGet, iProcessID, PID" blank and so on down the line. My humble opinion is that one of the "ControlGet, hwWindow" commands is failing, which leads the other functions to fail.
User avatar
Flipeador
Posts: 1083
Joined: 15 Nov 2014, 21:31
GitHub: Flipeador
Location: Argentina
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

10 Mar 2018, 22:38

It works well on my Windows 10. :)

I have made a version for AHK v2:
Updated: 2019/06/07.

Code: Select all

/*
    Restores or gets the position and text of all icons on the desktop.
    Parameters:
        Data:
            Specify the returned object to restore the position of the icons.
            Omit this parameter to retrieve the information.
    Return value:
        If it is to be restored, it returns the number of icons moved; Otherwise it returns an object.
        The object contains the following format: {IconText: {X,Y}}.
        If the function fails, the return value is zero. To get extended error information, check ErrorLevel.
    Credits:
        https://autohotkey.com/boards/viewtopic.php?f=6&t=3529
*/
DesktopIcons(Data := 0)
{
    local

    if !(hListView := DesktopGetListView())
        return 0

    ; LVM_GETITEMCOUNT message.
    ; https://docs.microsoft.com/en-us/windows/desktop/Controls/lvm-getitemcount.
    ItemCount := SendMessage(0x1004,,, hListView)  ; Gets the number of icons on the desktop.

    ; Opens the process of «hListView» with PROCESS_VM_READ|PROCESS_VM_OPERATION|PROCESS_VM_WRITE.
    ProcessId := WinGetPID("ahk_id" . hListView)
    hProcess  := DllCall("Kernel32.dll\OpenProcess", "UInt", 0x00000038, "Int", FALSE, "UInt", ProcessId, "Ptr")
    if !hProcess
        return !(ErrorLevel := 1)

    Buffer := BufferAlloc(2*32767)  ; LVITEMW.pszText: Buffer that receives the item text.
    POINT  := BufferAlloc(8)        ; POINT structure: https://docs.microsoft.com/en-us/windows/desktop/api/windef/ns-windef-tagpoint.

    ; LVITEMW structure.
    ; https://docs.microsoft.com/en-us/windows/desktop/api/commctrl/ns-commctrl-lvitemw.
    Address := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "Ptr", 0, "Ptr", A_PtrSize==4?72:88, "UInt", 0x1000, "UInt", 0x0004, "Ptr")
    ; LVITEMW.pszText: Buffer in «hProcess» that receives the item text.
    pBuffer := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "Ptr", 0, "Ptr", Buffer.Size, "UInt", 0x1000, "UInt", 0x0004, "Ptr")
    ; Writes the address of the buffer and its size in the LVITEMW structure.
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "Ptr", Address+16+A_PtrSize, "PtrP", pBuffer, "Ptr", A_PtrSize, "Ptr", 0)   ; LVITEMW.pszText.
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "Ptr", Address+16+2*A_PtrSize, "IntP", Buffer.Size//2, "Ptr", 4, "Ptr", 0)  ; LVITEMW.cchTextMax.
    
    ; ==============================================================================================================
    ; Save
    ; ==============================================================================================================
    if (!Data)
    {
        Data := {}
        Loop (ItemCount)
        {
            ; LVM_GETITEMPOSITION message.
            ; https://docs.microsoft.com/en-us/windows/desktop/controls/lvm-getitemposition.
            SendMessage(0x1010, A_Index-1, Address, hListView)  ; Gets the position of the (A_Index-1)th icon.
            ; Reads the position written in «Address» to the 'POINT' buffer of our script.
            DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "Ptr", Address, "Ptr", POINT, "Ptr", POINT.Size, "Ptr", 0)

            ; LVM_GETITEMTEXT message.
            ; https://docs.microsoft.com/en-us/windows/desktop/Controls/lvm-getitemtext.
            SendMessage(0x1073, A_Index-1, Address, hListView)  ; Gets the text of the (A_Index-1)th icon.
            ; Read the text written in «Address» (LVITEMW.pszText/pBuffer) to the 'Buffer' buffer of our script.
            DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "Ptr", pBuffer, "Ptr", Buffer, "Ptr", Buffer.Size, "Ptr", 0)
            
            ObjRawSet(Data, StrGet(Buffer,"UTF-16")
                          , { X:NumGet(POINT,"Int") , Y:Numget(POINT,4,"Int") }
                     )
        }
    }

    ; ==============================================================================================================
    ; Restore
    ; ==============================================================================================================
    else
    {
        Count := 0
        Loop (ItemCount)
        {
            ; LVM_GETITEMTEXT message.
            ; https://docs.microsoft.com/en-us/windows/desktop/Controls/lvm-getitemtext.
            SendMessage(0x1073, A_Index-1, Address, hListView)  ; Gets the text of the (A_Index-1)th icon.
            ; Read the text written in «Address» (LVITEMW.pszText/pBuffer) to the 'Buffer' buffer of our script.
            DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "Ptr", pBuffer, "Ptr", Buffer, "Ptr", Buffer.Size, "Ptr", 0)

            if ObjHasKey(Data,ItemText:=StrGet(Buffer,"UTF-16"))
            {
                ; LVM_SETITEMPOSITION message.
                ; https://docs.microsoft.com/en-us/windows/desktop/Controls/lvm-setitemposition.
                ; The LOWORD specifies the new x-position of the item's upper-left corner, in view coordinates.
                ; The HIWORD specifies the new y-position of the item's upper-left corner, in view coordinates.
                Count += SendMessage(0x100F, A_Index-1, Data[ItemText].X&0xFFFF|(Data[ItemText].Y&0xFFFF)<<16, hListView)
            }
        }
        Data := Count
    }
    
    ; ==============================================================================================================
    DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "Ptr", Address, "Ptr", 0, "UInt", 0x8000)
    DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "Ptr", pBuffer, "Ptr", 0, "UInt", 0x8000)
    DllCall("Kernel32.dll\CloseHandle", "Ptr", hProcess)

    return Data
}





/*
    Retrieves the position of a single icon on the desktop with the specified text.
    Parameters:
        ItemName:
            The text of an icon (file name) on the desktop.
    Return value:
        If the function succeeds, the return value is non-zero.
        If the function fails, the return value is zero. To get extended error information, check ErrorLevel.
*/
DesktopSetIconPos(ItemName, X, Y)
{
    local DeskIcons := DesktopIcons()

    if !DeskIcons || !ObjHasKey(DeskIcons,ItemName)
        return DeskIcons ? !(ErrorLevel := -1) : 0

    ObjRawSet(DeskIcons, ItemName, {x:x, y:y})
    return DesktopIcons(DeskIcons)
}





/*
    Retrieves the position of a single icon on the desktop with the specified text.
    Parameters:
        ItemName:
            The text of an icon (file name) on the desktop.
    Return value:
        If the function succeeds, the return value is an object with the keys 'X' and 'Y'.
        If the function fails, the return value is zero. To get extended error information, check ErrorLevel.
*/
DesktopGetIconPos(ItemName)
{
    local DeskIcons := DesktopIcons()
    return !DeskIcons ? 0
         : !ObjHasKey(DeskIcons,ItemName) ? !(ErrorLevel := -1)
         : DeskIcons[ItemName]
}





/*
    Gets the control where icons are displayed on the desktop.
    Return value:
        If the function succeeds, the return value is the ListView control handle.
        If the function fails, the return value is zero.
*/
DesktopGetListView()
{
    local
    if (hListView := ControlGetHwnd("SysListView321", "ahk_class Progman"))
        return hListView
    if (hListView := DllCall("User32.dll\FindWindowEx","Ptr",DllCall("User32.dll\FindWindowEx","Ptr"
    ,DllCall("User32.dll\GetShellWindow","Ptr"),"Ptr",0,"Str","SHELLDLL_DefView","Ptr",0,"Ptr"),"Ptr",0,"Str","SysListView32","Ptr",0,"Ptr"))
        return hListView
    For i, WindowId in WinGetList("ahk_class WorkerW")
        if (WindowId := DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SHELLDLL_DefView", "Ptr", 0, "Ptr"))
            return DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SysListView32", "Ptr", 0, "Ptr")
    return 0
}
Example:

Code: Select all

MsgBox(Format("A_IsAdmin:`s{}.",A_IsAdmin?"TRUE":"FALSE"))
For IconText, Point in Data := DesktopIcons()
    IconList .= Format("{}`s({};{})`n", IconText, Point.X, Point.Y)
MsgBox(Format("DesktopIcons()`n{}{}{1}Try moving some icons.","------------------------------`n",IconList))
MsgBox(Format("Restored:`s{}",DesktopIcons(Data)))
Updates: https://github.com/flipeador/Library-AutoHotkey/blob/master/sys/Desktop.ahk.
joedf⠀ wrote:Thanks for post this Flipeador.
No problem, thanks to you for sharing the code ;)
Windws 1♂ Pro 64-Bits I make scripts for AHKv2 (my v2 compiler) & WIN_7+ Spanish Argentina
(If any of my code written for v2 has stopped working, send me a private message. I appreciate that you correct my English.)
User avatar
joedf
Posts: 7048
Joined: 29 Sep 2013, 17:08
Facebook: J0EDF
Google: +joedf
GitHub: joedf
Location: Canada
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

12 Mar 2018, 08:29

Thanks for post this Flipeador.
I will link to it in the first post along with some kind of fix when I find the time :b
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500 @ 3.00 GHz, 16GB DDR4 2133 MHz, NVIDIA GTX 1060 6GB | [About Me] | [ASPDM - StdLib Distribution]
[Populate the AHK MiniCity!] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library] | [About the AHK Foundation]
ahbi
Posts: 16
Joined: 15 Jun 2016, 17:11

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

06 Apr 2018, 23:07

DeskIcons() is nice as far as it goes, but I am at a loss as to how to take the next step, setting arbitrary icon positions.

If I dump out coords I get

Code: Select all

This PC:47318090
Recycle Bin:53150794
Handbrake:64816202
That 64816202 number (for Handbrake) must be a coordinate or related to one.

And by adding the following to DeskIcons()

Code: Select all

DllCall("ReadProcessMemory", "ptr", hProcess, "ptr", pItemCoord, "UInt", &iCoord, "UInt", 8, "UIntP", cbReadWritten)
            THE_ITEMNAME := A_LoopField
            THE_X_COORD := NumGet(iCoord,"Int")
            THE_Y_COORD := Numget(iCoord, 4,"Int")
ret .= A_LoopField ":" (NumGet(iCoord,"Int") & 0xFFFF) | ((Numget(iCoord, 4,"Int") & 0xFFFF) << 16) "`n"
I can see that Handbrake (via iCoord) is at X: 1098 & Y: 989, which are Relative positions. Checking with WinSpy that agrees.

But I am not sure how I arbitrarily set a coordinate for the icon.

If I want to move the Handbrake icon from its original position to ... say .. X: 2000 & Y: 1500, how would I go about that?

What is that packing and bit shifting that occurs with the ret variable?

Thanks
User avatar
Flipeador
Posts: 1083
Joined: 15 Nov 2014, 21:31
GitHub: Flipeador
Location: Argentina
Contact:

MAKEWORD | MAKELONG | MAKELONG64 | LOWORD | HIWORD | LOBYTE | HIBYTE | LOLONG | HILONG

07 Apr 2018, 08:28

ahbi wrote:If I want to move the Handbrake icon from its original position to ... say .. X: 2000 & Y: 1500, how would I go about that?
Do you want to set the position of a specific icon?; We need another function for this (Not necessarily, but it would be fine). *I have added SetDeskIconPos to my previous Script.
ahbi wrote:What is that packing and bit shifting that occurs with the ret variable?
See the lParam parameter of the LVM_SETITEMPOSITION message. You need to package the coordinates (x;y) in a 32-bit integer. See MAKELONG macro | Packaging values in DWORD.

Code: Select all

/*
    #define MAKEWORD(a, b)      ((WORD)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | ((WORD)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8))
    n := MAKEWORD(0, 255), MsgBox("WORD " . n . "; LOBYTE " . LOBYTE(n) . "; HIBYTE " . HIBYTE(n))
*/
MAKEWORD(byte_low, byte_high := 0)
{
    Return (byte_low & 0xFF) | ((byte_high & 0xFF) << 8)
} ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms632663(v=vs.85).aspx

/*
    #define MAKELONG(a, b)      ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
    n := MAKELONG(0, 65535), MsgBox("LONG " . n . "; LOWORD " . LOWORD(n) . "; HIWORD " . HIWORD(n))
*/
MAKELONG(short_low, short_high := 0)
{
    Return (short_low & 0xFFFF) | ((short_high & 0xFFFF) << 16)
} ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms632660(v=vs.85).aspx

/*
    #define MAKELONG64(hi, lo)    ((LONGLONG(DWORD(hi) & 0xffffffff) << 32 ) | LONGLONG(DWORD(lo) & 0xffffffff))
    n := MAKELONG64(0, 4294967295), MsgBox("LONG64 " . n . "; LOLONG " . LOLONG(n) . "; HILONG " . HILONG(n))
*/
MAKELONG64(long_low, long_high := 0)
{
    Return (long_low & 0xFFFFFFFF) | ((long_high & 0xFFFFFFFF) << 32)  
}

LOWORD(l)
{
    Return l & 0xFFFF
} ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms632659(v=vs.85).aspx

HIWORD(l)
{
    Return (l >> 16) & 0xFFFF
} ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms632657(v=vs.85).aspx

LOBYTE(w)
{
    Return w & 0xFF
} ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms632658(v=vs.85).aspx

HIBYTE(w)
{
    Return (w >> 8) & 0xFF
} ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms632656(v=vs.85).aspx

LOLONG(ll)
{
    Return ll & 0xFFFFFFFF
}

HILONG(ll)
{
    Return (ll >> 32) & 0xFFFFFFFF
}
Windws 1♂ Pro 64-Bits I make scripts for AHKv2 (my v2 compiler) & WIN_7+ Spanish Argentina
(If any of my code written for v2 has stopped working, send me a private message. I appreciate that you correct my English.)
iPhilip
Posts: 384
Joined: 02 Oct 2013, 12:21

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

09 Jul 2018, 18:27

Hi Folks,

Can this script be adapted to get the dimensions of the icons as well, perhaps through LVM_GETSUBITEMRECT? Ultimately, I am trying to find a way to get the name of the icon under the mouse.

Thank you,

iPhilip
Windows 7 Pro (64 bit) - AutoHotkey v1.1+ (Unicode 32-bit)
User avatar
jeeswg
Posts: 6397
Joined: 19 Dec 2016, 01:58
Location: UK

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

09 Jul 2018, 22:01

- Here's a way to get the name of the file under the cursor via Acc:
Explorer: get name of file under cursor - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=51788

- Some information re. view modes and hence icon sizes:
Reading Win 10 File Explorer View Mode - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=5&t=28304
- There are techniques here to get a window object for the Desktop/Explorer windows.
Explorer window interaction (folder windows/Desktop, file/folder enumeration/selection/navigation/creation) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=35041
Last edited by jeeswg on 10 Jul 2018, 00:30, edited 2 times in total.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
iPhilip
Posts: 384
Joined: 02 Oct 2013, 12:21

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

10 Jul 2018, 00:11

Thank you jeeswg,

I appreciate your resourcefulness. I look forward to trying that in the morning.

iPhilip
Windows 7 Pro (64 bit) - AutoHotkey v1.1+ (Unicode 32-bit)
vanipede
Posts: 5
Joined: 10 Jan 2019, 17:16

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

10 Jan 2019, 17:22

Does anyone know of a simple way to keep the icon location data persistent between reboots. Every time my desktop gets redirected and I log in the icons are changed, so it would be nice to be able to save the config between boots/exiting the program.
User avatar
joedf
Posts: 7048
Joined: 29 Sep 2013, 17:08
Facebook: J0EDF
Google: +joedf
GitHub: joedf
Location: Canada
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

13 Jan 2019, 21:02

Yeah I've had that issue before, I had made a script to save the icon positions to a file, and I would simply load it and restore the positions from the file with this function.
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500 @ 3.00 GHz, 16GB DDR4 2133 MHz, NVIDIA GTX 1060 6GB | [About Me] | [ASPDM - StdLib Distribution]
[Populate the AHK MiniCity!] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library] | [About the AHK Foundation]
Walli
Posts: 4
Joined: 14 Jan 2019, 06:19
Location: Germany, Hannover

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

14 Jan 2019, 06:32

Is there any solution for the "OpenProcess" issue?

Edit:
For one machine i got it, i changed following

Code: Select all

	ControlGet, hwWindow, HWND,, SysListView321, ahk_class Progman
	if !hwWindow ; #D mode
		ControlGet, hwWindow, HWND,, SysListView321, A
to:

Code: Select all

	ControlGet, hwWindow, HWND,, SysListView321, ahk_class Progman
	if !hwWindow ; #D mode
		ControlGet, hwWindow, HWND,, SysListView321, A
	if !hwWindow
		ControlGet, hwWindow, HWND,, SysListView321, ahk_class WorkerW
User avatar
joedf
Posts: 7048
Joined: 29 Sep 2013, 17:08
Facebook: J0EDF
Google: +joedf
GitHub: joedf
Location: Canada
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

14 Jan 2019, 10:42

I’m not sure. I haven’t done much testing. Does it still happen occasionally? Or all the time?
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500 @ 3.00 GHz, 16GB DDR4 2133 MHz, NVIDIA GTX 1060 6GB | [About Me] | [ASPDM - StdLib Distribution]
[Populate the AHK MiniCity!] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library] | [About the AHK Foundation]
Walli
Posts: 4
Joined: 14 Jan 2019, 06:19
Location: Germany, Hannover

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

14 Jan 2019, 13:19

After i added

Code: Select all

	if !hwWindow
		ControlGet, hwWindow, HWND,, SysListView321, ahk_class WorkerW
it works on every machine.

What does not work:
If i'm logged in as normal domainuser and run the script with elevated rights as domainadmin. In that case it looks like the OpenProcess function denies access.
Walli
Posts: 4
Joined: 14 Jan 2019, 06:19
Location: Germany, Hannover

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

14 Jan 2019, 13:56

@vanipede

Code: Select all

Save:
coords := DeskIcons()
FileDelete, %ProgramData%\TEMP\desktopicons.txt
FileAppend, %coords%, %ProgramData%\TEMP\desktopicons.txt 
return

Code: Select all

Restore:
FileRead, coords, %ProgramData%\TEMP\desktopicons.txt
DeskIcons(coords)
return
User avatar
joedf
Posts: 7048
Joined: 29 Sep 2013, 17:08
Facebook: J0EDF
Google: +joedf
GitHub: joedf
Location: Canada
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

14 Jan 2019, 22:07

Walli wrote:
14 Jan 2019, 13:19
What does not work:
If i'm logged in as normal domainuser and run the script with elevated rights as domainadmin. In that case it looks like the OpenProcess function denies access.
Interesting... perhaps it has something to do with dwDesiredAccess?
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500 @ 3.00 GHz, 16GB DDR4 2133 MHz, NVIDIA GTX 1060 6GB | [About Me] | [ASPDM - StdLib Distribution]
[Populate the AHK MiniCity!] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library] | [About the AHK Foundation]
Walli
Posts: 4
Joined: 14 Jan 2019, 06:19
Location: Germany, Hannover

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

15 Jan 2019, 06:33

I played a little with dwDesiredAccess. The minimum we need is:

Code: Select all

hProcess := DllCall("OpenProcess"	, "UInt",	0x18			; VirtualMemoryOperation|VirtualMemoryRead
									, "Int",	FALSE			; inherit = false
									, "ptr",	iProcessID)
It also works with the max of 0x1F0FFF.

But it doesn't help in my case with elevated rights.

Now i got it:
It works, if you join the normal user to the administrators group.
So i have to make a standalone exe-file, which runs with normal rights.
User avatar
joedf
Posts: 7048
Joined: 29 Sep 2013, 17:08
Facebook: J0EDF
Google: +joedf
GitHub: joedf
Location: Canada
Contact:

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

15 Jan 2019, 10:05

Ahhh okay, I see. Weird security rights system with windows :b
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500 @ 3.00 GHz, 16GB DDR4 2133 MHz, NVIDIA GTX 1060 6GB | [About Me] | [ASPDM - StdLib Distribution]
[Populate the AHK MiniCity!] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library] | [About the AHK Foundation]
vanipede
Posts: 5
Joined: 10 Jan 2019, 17:16

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

16 Jan 2019, 12:01

Walli wrote:
14 Jan 2019, 13:56
@vanipede


Thank you for replying so quickly. That is a clean implementation of what I am trying to do!
Unfortunately I get an error everytime I try to run the script.
--------------------------------------------------------------------------------------
Error at line 3.

Line Text: FileDelete, %ProgramData%\TEMP\desktopicons.txt
Error: Function calls require a space or '(', Use comma only between parameters.
The program will exit.
-----------------------------------------------------------------------------------------------------

Code: Select all

Save:
coords := DeskIcons()
FileDelete, %ProgramData%\TEMP\desktopicons.txt
FileAppend, %coords%, %ProgramData%\TEMP\desktopicons.txt 
return

Code: Select all

Restore:
FileRead, coords, %ProgramData%\TEMP\desktopicons.txt
DeskIcons(coords)
return

Code: Select all

; save positions
!s::coords := DeskIcons()
FileDelete, %ProgramData%\TEMP\desktopicons.txt
FileAppend, %coords%, %ProgramData%\TEMP\desktopicons.txt 
return


MsgBox now move the icons around yourself
; load positions
!l::FileRead, coords, %ProgramData%\TEMP\desktopicons.txt
DeskIcons(coords)
return

MsgBox "A_IsAdmin: " . A_IsAdmin
For ItemText, POINT in Data := DeskIcons()
    Icons .= ItemText . " (" . POINT.x . ";" . POINT.y . ")`n"
MsgBox "DeskIcons()`n------------------------------`n" . Icons
DeskIcons(Data)

DeskIcons(Data := 0)    ; CREDITS : https://autohotkey.com/boards/viewtopic.php?f=6&t=3529
{
    static PROCESS_VM_READ     := 0x0010, PROCESS_VM_OPERATION  := 0x0008, PROCESS_VM_WRITE    := 0x0020
         , MEM_COMMIT          := 0x1000, PAGE_READWRITE        := 0x0004 ;, MEM_RELEASE         := 0x8000
         , LVM_GETITEMCOUNT    := 0x1004, LVM_GETITEMPOSITION   := 0x1010, LVM_SETITEMPOSITION := 0x100F, LVM_GETITEMTEXTW := 0x1073

    ; recuperamos el identificador del control SysListView que muestra los iconos en el escritorio
    Local WindowId := GetDeskListView()    ; ControlGetHwnd("SysListView321", "ahk_class Progman")
    If (!WindowId)
        Return "SysListView321?"

    ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761044(v=vs.85).aspx
    ; recuperamos la cantidad de iconos en el escritorio
    Local ItemCount := DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMCOUNT, "Ptr", 0, "Ptr", 0)
    If (!ItemCount)
        Return "ItemCount #0"

    Local ProcessId := WinGetPID("ahk_id" . WindowId)    ; recuperamos el identificador del proceso perteneciente al control SysListView
        ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx
        ; abrimos el proceso para realizar operaciones de lectura y escritura en su memoria
        , hProcess  := DllCall("Kernel32.dll\OpenProcess", "UInt", PROCESS_VM_READ|PROCESS_VM_OPERATION|PROCESS_VM_WRITE, "Int", FALSE, "UInt", ProcessId, "Ptr")
    If (!hProcess)
        Return "OpenProcess ERROR"

    ; https://msdn.microsoft.com/en-us/library/windows/desktop/aa366890(v=vs.85).aspx
    ; reservamos memoria para el proceso para almacenar datos en ella, conociendo su posición en memoria podemos escribir y leer datos de forma segura
    ; para leer y escribir datos en la memoria de otro proceso, debemos utilizar las funciones WriteProcessMemory y ReadProcessMemory, no podemos hacerlo directamente en una variable de nuestro script
    ; ya que la memoria no es compartida y no podemos acceder a la memoria de otro proceso con las funciones incorporadas NumGet/NumPut, solo haría que nuestro Script terminase abruptamente
    ; entonces, reservamos memoria para utilizar de forma segura en el espacio del proceso deseado, la idea no es escribir en cualquier parte de la memoria de otro proceso sino en una solo para nuestro propósito
    ; las funcion "VirtualAllocEx" es como si llamásemos a "VarSetCapacity(VarBuff, size)" en ese proceso y devolviese la dirección de memoria de "VarBuff".
    Local Address := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "UPtr", 0, "UPtr", A_PtrSize == 4 ? 72 : 88, "UInt", MEM_COMMIT, "UInt", PAGE_READWRITE, "UPtr")    ; espacio para la estructura LVITEM
    Local   pBuff := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "UPtr", 0, "UPtr", 520, "UInt", MEM_COMMIT, "UInt", PAGE_READWRITE, "UPtr")    ; espacio para almacenar el texto de un elemento (icono)
    If (!Address || !pBuff)
        Return Error("VirtualAllocEx ERROR")

    ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms681674(v=vs.85).aspx
    ; escribimos ciertos datos en la memoria reservada para la estructura LVITEM
    Local NumberOfBytesWritten, NumberOfBytesRead
    ; almacenamos la dirección de mememoria de pBuff en la estructura LVITEM, que debe estar en la posición "16 + A_PtrSize" a partir de "Address"
    ; utilizamos "UPtrP, pBuff" ya que en este parámetro de "WriteProcessMemory" se debe especificar un puntero (dirección de memoria) que contiene los datos a escribir; por lo tanto, sabiendo que pBuff contiene
    ; la dirección de memoria que queremos escribir en "LVITEM", debemos pasar la dirección de memoria que contiene la dirección de memoria almacenada en pBuff, esto es lo mismo que "UPtr, &pBuff"
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "UPtr", Address + 16 + A_PtrSize, "UPtrP", pBuff, "UPtr", A_PtrSize, "UPtrP", NumberOfBytesWritten)
    ; luego almacenamos la cantidad de caracteres (UTF-16) máximos que serán escritos, si reservamos memoria para 520 bytes, en caracteres seria 520//2, lo que nos dá 260
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "UPtr", Address + 16 + A_PtrSize*2, "IntP", 260, "UPtr", 4, "UPtrP", NumberOfBytesWritten)


    ; ==============================================================================================================
    ; Save
    ; ==============================================================================================================
    Local Buffer, POINT
    VarSetCapacity(Buffer, 520), VarSetCapacity(POINT, 8)
    If (!IsObject(Data))
    {
        Data := {}
        Loop (ItemCount)
        {
            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761048(v=vs.85).aspx
            ; recuperamos la posición x,y del icono con el índice "A_Index - 1" y le decimos a "SendMessage" que escriba los datos en la dirección de memoria que contiene "Address"
            ; nota: en este caso, utilizamos "Address" para dos propósitos, almacenar la estructura "POINT" (8 bytes) para recuperar la posición del elemento, y a su vez almacenar a la estructura LVITEM,
            ; que utilizamos mas abajo para recuperar el texto (aprovechamos el espacio reservado, ya que la estructura "POINT" (8 bytes) entra en la estructura "LVITEM" (48+A_PtrSize*3 bytes))
            If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMPOSITION, "Int", A_Index-1, "UPtr", Address))
                Return Error("LVM_GETITEMPOSITION Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
            ; la posición son dos valores (x,y) de 4 bytes c/u (int, estructura POINT), por lo tanto le especificamos a la función "ReadProcessMemory" que lea 8 bytes y almacene los datos leídos en "POINT"
            ; que es una variable que declaramos anteriormente en nuestro script y que puede almacenar hasta 8 bytes, exactamente lo que necesitamos; como aclaramos anteriormente, no podemos leer los datos
            ; directamente de la dirección de memoria almacenada en "Address" ya que esa parte de la memoria no pertenece a nuestro Script y no tenemos privilegios para acceder a ella, "ReadProcessMemory" si los tiene
            If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", Address, "UPtr", &POINT, "UPtr", 8, "UPtrP", NumberOfBytesRead))
                Return Error("ReadProcessMemory #1 Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761055(v=vs.85).aspx
            ; recuperamos el texto del elemento (icono) en el control SysListView, "LVM_GETITEMTEXTW" escribe el texto en la dirección de memoria que contiene "pBuff", que almacenamos en la estructura "LVITEM"
            ; la estructura "LVITEM", en este caso, estaría representada por "Address", que contiene la dirección de memoria que apunta al comienzo de esta estructura
            If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMTEXTW, "Int", A_Index-1, "UPtr", Address))
                Return Error("LVM_GETITEMTEXTW Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
            ; leemos el texto que se ha escrito en la dirección de memoria que contiene "pBuff" y la escribimos en la dirección de memoria de "Buffer", nuestra variable a la cual si tenemos acceso
            If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", pBuff, "UPtr", &Buffer, "UPtr", 520, "UPtrP", NumberOfBytesRead))
                Return Error("ReadProcessMemory #2 Index #" . A_Index . " ERROR")
            
            ; luego, leemos el texto y posición del elemento para guardarlas en el objeto "Data"
            ObjRawSet(Data, StrGet(&Buffer, "UTF-16"), {x: NumGet(&POINT, "Int"), y: Numget(&POINT + 4, "Int")})
        }

        Return Error(Data)    ; OK! devolvemos el objeto "Data", cuyas claves contienen el texto de cada elemento (icono) y su valor la posición de este
    }


    ; ==============================================================================================================
    ; Restore
    ; ==============================================================================================================
    ; aquí restauramos los iconos a la posición almacenada en "Data", se aplica la misma lógica que arriba
    Local ItemText
    Loop (ItemCount)
    {
        ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761055(v=vs.85).aspx
        If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMTEXTW, "Int", A_Index-1, "UPtr", Address))
            Return Error("LVM_GETITEMTEXTW Index #" . A_Index . " ERROR")

        ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
        If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", pBuff, "UPtr", &Buffer, "UPtr", 520, "UPtrP", NumberOfBytesRead))
            Return Error("ReadProcessMemory Index #" . A_Index . " ERROR")

        If (ObjHasKey(Data, ItemText := StrGet(&Buffer, "UTF-16")))    ; determinamos si el texto del elemento actual se encuentra en el objeto "Data"
            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761192(v=vs.85).aspx
            ; establecemos la posición del elemento encontrado
            ; The LOWORD specifies the new x-position of the item's upper-left corner, in view coordinates.
            ; The HIWORD specifies the new y-position of the item's upper-left corner, in view coordinates.
            DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_SETITEMPOSITION, "Int", A_Index-1, "UPtr", Data[ItemText].x & 0xFFFF | (Data[ItemText].y & 0xFFFF) << 16)
    }
    Return Error(TRUE)    ; OK!


    ; ==============================================================================================================
    ; Nested Functions
    ; ==============================================================================================================
    Error(Msg)
    {
        static MEM_RELEASE := 0x8000
        If (Address)    ; liberamos la memoria reservada Address para la aplicación
            If (!DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "UPtr", Address, "Ptr", 0, "UInt", MEM_RELEASE))
                MsgBox("VirtualFreeEx #1 ERROR!",, 0x2010), ExitApp()
        If (pBuff)    ; liberamos la memoria reservada pBuff para la aplicación
            If (!DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "UPtr", pBuff, "Ptr", 0, "UInt", MEM_RELEASE))
                MsgBox("VirtualFreeEx #2 ERROR!",, 0x2010), ExitApp()
        If (hProcess)    ; cerramos el Handle del proceso
            If (!DllCall("Kernel32.dll\CloseHandle", "Ptr", hProcess))
                MsgBox("CloseHandle ERROR!",, 0x2010), ExitApp()
        Return Msg
    }
}





/*
    Recupera el identificador del control ListView donde se visualizan los iconos en el escritorio.
*/
GetDeskListView()
{
    Local hListView := ControlGetHwnd("SysListView321", "ahk_class Progman")
    If (hListView)
        Return hListView
    If (hListView := DllCall("User32.dll\FindWindowEx", "Ptr", DllCall("User32.dll\FindWindowEx", "Ptr", DllCall("User32.dll\GetShellWindow", "Ptr"), "Ptr", 0, "Str", "SHELLDLL_DefView", "Ptr", 0, "Ptr"), "Ptr", 0, "Str", "SysListView32", "Ptr", 0, "Ptr"))
        Return hListView
    For Each, WindowId in WinGetList("ahk_class WorkerW")    ; WIN_8 && WIN_10
        If (WindowId := DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SHELLDLL_DefView", "Ptr", 0, "Ptr"))
            Return DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SysListView32", "Ptr", 0, "Ptr")
    Return FALSE
}





SetDeskIconPos(ItemName, X, Y)
{
    Local DeskIcons := DeskIcons()
    If (!IsObject(DeskIcons))
        Return DeskIcons

    If (!ObjHasKey(DeskIcons, ItemName))
        Return "ItemName doesn't exist"

    ObjRawSet(DeskIcons, ItemName, {x: x, y: y})
    Return DeskIcons(DeskIcons)
}





GetDeskIconPos(ItemName)
{
    Local DeskIcons := DeskIcons()
    If (!IsObject(DeskIcons))
        Return DeskIcons
    If (!ObjHasKey(DeskIcons, ItemName))
        Return "ItemName doesn't exist"

    Return {X: DeskIcons[ItemName].X, Y: DeskIcons[ItemName].Y}
}
Attachments
error.png
error.png (9.42 KiB) Viewed 1034 times
vanipede
Posts: 5
Joined: 10 Jan 2019, 17:16

Re: [x64 & x32 fix] DeskIcons - Get/Set Desktop Icon Positions

16 Jan 2019, 12:01

Walli wrote:
14 Jan 2019, 13:56
@vanipede


Thank you for replying so quickly. That is a clean implementation of what I am trying to do!
Unfortunately I get an error everytime I try to run the script.
--------------------------------------------------------------------------------------
Error at line 3.

Line Text: FileDelete, %ProgramData%\TEMP\desktopicons.txt
Error: Function calls require a space or '(', Use comma only between parameters.
The program will exit.
-----------------------------------------------------------------------------------------------------

Code: Select all

Save:
coords := DeskIcons()
FileDelete, %ProgramData%\TEMP\desktopicons.txt
FileAppend, %coords%, %ProgramData%\TEMP\desktopicons.txt 
return

Code: Select all

Restore:
FileRead, coords, %ProgramData%\TEMP\desktopicons.txt
DeskIcons(coords)
return

Code: Select all

; save positions
!s::coords := DeskIcons()
FileDelete, %ProgramData%\TEMP\desktopicons.txt
FileAppend, %coords%, %ProgramData%\TEMP\desktopicons.txt 
return


MsgBox now move the icons around yourself
; load positions
!l::FileRead, coords, %ProgramData%\TEMP\desktopicons.txt
DeskIcons(coords)
return

MsgBox "A_IsAdmin: " . A_IsAdmin
For ItemText, POINT in Data := DeskIcons()
    Icons .= ItemText . " (" . POINT.x . ";" . POINT.y . ")`n"
MsgBox "DeskIcons()`n------------------------------`n" . Icons
DeskIcons(Data)

DeskIcons(Data := 0)    ; CREDITS : https://autohotkey.com/boards/viewtopic.php?f=6&t=3529
{
    static PROCESS_VM_READ     := 0x0010, PROCESS_VM_OPERATION  := 0x0008, PROCESS_VM_WRITE    := 0x0020
         , MEM_COMMIT          := 0x1000, PAGE_READWRITE        := 0x0004 ;, MEM_RELEASE         := 0x8000
         , LVM_GETITEMCOUNT    := 0x1004, LVM_GETITEMPOSITION   := 0x1010, LVM_SETITEMPOSITION := 0x100F, LVM_GETITEMTEXTW := 0x1073

    ; recuperamos el identificador del control SysListView que muestra los iconos en el escritorio
    Local WindowId := GetDeskListView()    ; ControlGetHwnd("SysListView321", "ahk_class Progman")
    If (!WindowId)
        Return "SysListView321?"

    ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761044(v=vs.85).aspx
    ; recuperamos la cantidad de iconos en el escritorio
    Local ItemCount := DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMCOUNT, "Ptr", 0, "Ptr", 0)
    If (!ItemCount)
        Return "ItemCount #0"

    Local ProcessId := WinGetPID("ahk_id" . WindowId)    ; recuperamos el identificador del proceso perteneciente al control SysListView
        ; https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx
        ; abrimos el proceso para realizar operaciones de lectura y escritura en su memoria
        , hProcess  := DllCall("Kernel32.dll\OpenProcess", "UInt", PROCESS_VM_READ|PROCESS_VM_OPERATION|PROCESS_VM_WRITE, "Int", FALSE, "UInt", ProcessId, "Ptr")
    If (!hProcess)
        Return "OpenProcess ERROR"

    ; https://msdn.microsoft.com/en-us/library/windows/desktop/aa366890(v=vs.85).aspx
    ; reservamos memoria para el proceso para almacenar datos en ella, conociendo su posición en memoria podemos escribir y leer datos de forma segura
    ; para leer y escribir datos en la memoria de otro proceso, debemos utilizar las funciones WriteProcessMemory y ReadProcessMemory, no podemos hacerlo directamente en una variable de nuestro script
    ; ya que la memoria no es compartida y no podemos acceder a la memoria de otro proceso con las funciones incorporadas NumGet/NumPut, solo haría que nuestro Script terminase abruptamente
    ; entonces, reservamos memoria para utilizar de forma segura en el espacio del proceso deseado, la idea no es escribir en cualquier parte de la memoria de otro proceso sino en una solo para nuestro propósito
    ; las funcion "VirtualAllocEx" es como si llamásemos a "VarSetCapacity(VarBuff, size)" en ese proceso y devolviese la dirección de memoria de "VarBuff".
    Local Address := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "UPtr", 0, "UPtr", A_PtrSize == 4 ? 72 : 88, "UInt", MEM_COMMIT, "UInt", PAGE_READWRITE, "UPtr")    ; espacio para la estructura LVITEM
    Local   pBuff := DllCall("Kernel32.dll\VirtualAllocEx", "Ptr", hProcess, "UPtr", 0, "UPtr", 520, "UInt", MEM_COMMIT, "UInt", PAGE_READWRITE, "UPtr")    ; espacio para almacenar el texto de un elemento (icono)
    If (!Address || !pBuff)
        Return Error("VirtualAllocEx ERROR")

    ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms681674(v=vs.85).aspx
    ; escribimos ciertos datos en la memoria reservada para la estructura LVITEM
    Local NumberOfBytesWritten, NumberOfBytesRead
    ; almacenamos la dirección de mememoria de pBuff en la estructura LVITEM, que debe estar en la posición "16 + A_PtrSize" a partir de "Address"
    ; utilizamos "UPtrP, pBuff" ya que en este parámetro de "WriteProcessMemory" se debe especificar un puntero (dirección de memoria) que contiene los datos a escribir; por lo tanto, sabiendo que pBuff contiene
    ; la dirección de memoria que queremos escribir en "LVITEM", debemos pasar la dirección de memoria que contiene la dirección de memoria almacenada en pBuff, esto es lo mismo que "UPtr, &pBuff"
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "UPtr", Address + 16 + A_PtrSize, "UPtrP", pBuff, "UPtr", A_PtrSize, "UPtrP", NumberOfBytesWritten)
    ; luego almacenamos la cantidad de caracteres (UTF-16) máximos que serán escritos, si reservamos memoria para 520 bytes, en caracteres seria 520//2, lo que nos dá 260
    DllCall("Kernel32.dll\WriteProcessMemory", "Ptr", hProcess, "UPtr", Address + 16 + A_PtrSize*2, "IntP", 260, "UPtr", 4, "UPtrP", NumberOfBytesWritten)


    ; ==============================================================================================================
    ; Save
    ; ==============================================================================================================
    Local Buffer, POINT
    VarSetCapacity(Buffer, 520), VarSetCapacity(POINT, 8)
    If (!IsObject(Data))
    {
        Data := {}
        Loop (ItemCount)
        {
            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761048(v=vs.85).aspx
            ; recuperamos la posición x,y del icono con el índice "A_Index - 1" y le decimos a "SendMessage" que escriba los datos en la dirección de memoria que contiene "Address"
            ; nota: en este caso, utilizamos "Address" para dos propósitos, almacenar la estructura "POINT" (8 bytes) para recuperar la posición del elemento, y a su vez almacenar a la estructura LVITEM,
            ; que utilizamos mas abajo para recuperar el texto (aprovechamos el espacio reservado, ya que la estructura "POINT" (8 bytes) entra en la estructura "LVITEM" (48+A_PtrSize*3 bytes))
            If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMPOSITION, "Int", A_Index-1, "UPtr", Address))
                Return Error("LVM_GETITEMPOSITION Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
            ; la posición son dos valores (x,y) de 4 bytes c/u (int, estructura POINT), por lo tanto le especificamos a la función "ReadProcessMemory" que lea 8 bytes y almacene los datos leídos en "POINT"
            ; que es una variable que declaramos anteriormente en nuestro script y que puede almacenar hasta 8 bytes, exactamente lo que necesitamos; como aclaramos anteriormente, no podemos leer los datos
            ; directamente de la dirección de memoria almacenada en "Address" ya que esa parte de la memoria no pertenece a nuestro Script y no tenemos privilegios para acceder a ella, "ReadProcessMemory" si los tiene
            If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", Address, "UPtr", &POINT, "UPtr", 8, "UPtrP", NumberOfBytesRead))
                Return Error("ReadProcessMemory #1 Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761055(v=vs.85).aspx
            ; recuperamos el texto del elemento (icono) en el control SysListView, "LVM_GETITEMTEXTW" escribe el texto en la dirección de memoria que contiene "pBuff", que almacenamos en la estructura "LVITEM"
            ; la estructura "LVITEM", en este caso, estaría representada por "Address", que contiene la dirección de memoria que apunta al comienzo de esta estructura
            If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMTEXTW, "Int", A_Index-1, "UPtr", Address))
                Return Error("LVM_GETITEMTEXTW Index #" . A_Index . " ERROR")

            ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
            ; leemos el texto que se ha escrito en la dirección de memoria que contiene "pBuff" y la escribimos en la dirección de memoria de "Buffer", nuestra variable a la cual si tenemos acceso
            If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", pBuff, "UPtr", &Buffer, "UPtr", 520, "UPtrP", NumberOfBytesRead))
                Return Error("ReadProcessMemory #2 Index #" . A_Index . " ERROR")
            
            ; luego, leemos el texto y posición del elemento para guardarlas en el objeto "Data"
            ObjRawSet(Data, StrGet(&Buffer, "UTF-16"), {x: NumGet(&POINT, "Int"), y: Numget(&POINT + 4, "Int")})
        }

        Return Error(Data)    ; OK! devolvemos el objeto "Data", cuyas claves contienen el texto de cada elemento (icono) y su valor la posición de este
    }


    ; ==============================================================================================================
    ; Restore
    ; ==============================================================================================================
    ; aquí restauramos los iconos a la posición almacenada en "Data", se aplica la misma lógica que arriba
    Local ItemText
    Loop (ItemCount)
    {
        ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761055(v=vs.85).aspx
        If (!DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_GETITEMTEXTW, "Int", A_Index-1, "UPtr", Address))
            Return Error("LVM_GETITEMTEXTW Index #" . A_Index . " ERROR")

        ; https://msdn.microsoft.com/es-es/library/windows/desktop/ms680553(v=vs.85).aspx
        If (!DllCall("Kernel32.dll\ReadProcessMemory", "Ptr", hProcess, "UPtr", pBuff, "UPtr", &Buffer, "UPtr", 520, "UPtrP", NumberOfBytesRead))
            Return Error("ReadProcessMemory Index #" . A_Index . " ERROR")

        If (ObjHasKey(Data, ItemText := StrGet(&Buffer, "UTF-16")))    ; determinamos si el texto del elemento actual se encuentra en el objeto "Data"
            ; https://msdn.microsoft.com/en-us/library/windows/desktop/bb761192(v=vs.85).aspx
            ; establecemos la posición del elemento encontrado
            ; The LOWORD specifies the new x-position of the item's upper-left corner, in view coordinates.
            ; The HIWORD specifies the new y-position of the item's upper-left corner, in view coordinates.
            DllCall("User32.dll\SendMessageW", "Ptr", WindowId, "UInt", LVM_SETITEMPOSITION, "Int", A_Index-1, "UPtr", Data[ItemText].x & 0xFFFF | (Data[ItemText].y & 0xFFFF) << 16)
    }
    Return Error(TRUE)    ; OK!


    ; ==============================================================================================================
    ; Nested Functions
    ; ==============================================================================================================
    Error(Msg)
    {
        static MEM_RELEASE := 0x8000
        If (Address)    ; liberamos la memoria reservada Address para la aplicación
            If (!DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "UPtr", Address, "Ptr", 0, "UInt", MEM_RELEASE))
                MsgBox("VirtualFreeEx #1 ERROR!",, 0x2010), ExitApp()
        If (pBuff)    ; liberamos la memoria reservada pBuff para la aplicación
            If (!DllCall("Kernel32.dll\VirtualFreeEx", "Ptr", hProcess, "UPtr", pBuff, "Ptr", 0, "UInt", MEM_RELEASE))
                MsgBox("VirtualFreeEx #2 ERROR!",, 0x2010), ExitApp()
        If (hProcess)    ; cerramos el Handle del proceso
            If (!DllCall("Kernel32.dll\CloseHandle", "Ptr", hProcess))
                MsgBox("CloseHandle ERROR!",, 0x2010), ExitApp()
        Return Msg
    }
}





/*
    Recupera el identificador del control ListView donde se visualizan los iconos en el escritorio.
*/
GetDeskListView()
{
    Local hListView := ControlGetHwnd("SysListView321", "ahk_class Progman")
    If (hListView)
        Return hListView
    If (hListView := DllCall("User32.dll\FindWindowEx", "Ptr", DllCall("User32.dll\FindWindowEx", "Ptr", DllCall("User32.dll\GetShellWindow", "Ptr"), "Ptr", 0, "Str", "SHELLDLL_DefView", "Ptr", 0, "Ptr"), "Ptr", 0, "Str", "SysListView32", "Ptr", 0, "Ptr"))
        Return hListView
    For Each, WindowId in WinGetList("ahk_class WorkerW")    ; WIN_8 && WIN_10
        If (WindowId := DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SHELLDLL_DefView", "Ptr", 0, "Ptr"))
            Return DllCall("User32.dll\FindWindowEx", "Ptr", WindowId, "Ptr", 0, "Str", "SysListView32", "Ptr", 0, "Ptr")
    Return FALSE
}





SetDeskIconPos(ItemName, X, Y)
{
    Local DeskIcons := DeskIcons()
    If (!IsObject(DeskIcons))
        Return DeskIcons

    If (!ObjHasKey(DeskIcons, ItemName))
        Return "ItemName doesn't exist"

    ObjRawSet(DeskIcons, ItemName, {x: x, y: y})
    Return DeskIcons(DeskIcons)
}





GetDeskIconPos(ItemName)
{
    Local DeskIcons := DeskIcons()
    If (!IsObject(DeskIcons))
        Return DeskIcons
    If (!ObjHasKey(DeskIcons, ItemName))
        Return "ItemName doesn't exist"

    Return {X: DeskIcons[ItemName].X, Y: DeskIcons[ItemName].Y}
}

Return to “Scripts and Functions”

Who is online

Users browsing this forum: No registered users and 40 guests