Jump to content
Sign in to follow this  
Blip

Getting event when file is dragged to input field

Recommended Posts

Blip

I have a GUI that has two input fields. The first one uses a button that users can hit to browse to a file, and that file and path get plugged into the first field.

When the Browse button is used my second input field does some _PathSplit magic to grab just the file name from that selected file, so the result would look something like:

First GUICtrlCreateInput:

[C:FilePathSelectedFileName.exe] [browse for file button]

Second GUICtrlCreateInput:

[selectedFileName]

This whole setup works really well, but my first input field also has the option for a file to be dragged and dropped. I'm trying to find some way to have the second field update and do a _SplitPath when a file is dragged into the first field.

(Less importantly, I'd like to find a way to have the second input update if the first field losses focus - for those users manually entering path & file in the first field.)

Any help or a point in the right direction would be amazing. Thanks.

Edited by Blip

Share this post


Link to post
Share on other sites
Blip

I should have done more research, just found $GUI_EVENT_DROPPED. Sorry to have wasted anyone's time. Still could use some advise for the manual user entries though. Or at least an idea of what is best practice for updating a GUI after a user entry.

Share this post


Link to post
Share on other sites
Nessie

Take a look to WM_DROPFILES and $GUI_EVENT_DROPPED

; *** Start added by AutoIt3Wrapper ***
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
; *** End added by AutoIt3Wrapper ***
#AutoIt3Wrapper_Add_Constants=n
;***************************************************
; by Lazycat
;***************************************************
#include <GUIConstants.au3>
Global $gaDropFiles[1], $str = ""

### Koda GUI section start ###
$hGUI = GUICreate("Test", 400, 200, 219, 178, -1, BitOR($WS_EX_ACCEPTFILES, $WS_EX_TOPMOST))
$hEdit = GUICtrlCreateEdit("", 5, 5, 390, 190)
GUICtrlSetState (-1, $GUI_DROPACCEPTED)
GUISetState(@SW_SHOW)
### Koda GUI section end ###

GUIRegisterMsg ($WM_DROPFILES, "WM_DROPFILES_FUNC")

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
    Case $GUI_EVENT_CLOSE
    Exit
    Case $GUI_EVENT_DROPPED
    $str = ""
    For $i = 0 To UBound($gaDropFiles) - 1
    $str &= "|" & $gaDropFiles[$i]
         Next
         GUICtrlSetData($hEdit,"Adding more" & @CRLF,1)
    GUICtrlSetData($hEdit, $str & @CRLF,1)
    EndSwitch
WEnd

Func WM_DROPFILES_FUNC($hWnd, $msgID, $wParam, $lParam)
    ConsoleWrite("aaaaaaaaaa" & @CRLF)
    Local $nSize, $pFileName
    Local $nAmt = DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", 0xFFFFFFFF, "ptr", 0, "int", 255)
    For $i = 0 To $nAmt[0] - 1
    $nSize = DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", $i, "ptr", 0, "int", 0)
    $nSize = $nSize[0] + 1
    $pFileName = DllStructCreate("char[" & $nSize & "]")
    DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", $i, "ptr", DllStructGetPtr($pFileName), "int", $nSize)
    ReDim $gaDropFiles[$i+1]
    $gaDropFiles[$i] = DllStructGetData($pFileName, 1)
    $pFileName = 0
    Next
EndFunc

Another example:

#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

Global $gaDropFiles[1]

#Region ### START Koda GUI section ### Form=
$hGUI = GUICreate("", 137, 131, -1, -1, BitOR($WS_DLGFRAME,$WS_POPUP,$WS_CLIPSIBLINGS), BitOR($WS_EX_ACCEPTFILES,$WS_EX_TOPMOST,$WS_EX_WINDOWEDGE))
GUISetBkColor(0xFFFFFF)
$hList = GUICtrlCreateLabel("Drop files here", 0, 0, 135, 121, BitOR($SS_CENTER,$SS_CENTERIMAGE), $GUI_WS_EX_PARENTDRAG)
GUICtrlSetState ($hList, $GUI_DROPACCEPTED)
$hContext = GUICtrlCreateContextMenu($hList)
$hExit = GUICtrlCreateMenuItem("Exit", $hContext)
#EndRegion ### END Koda GUI section ###

GUIRegisterMsg ($WM_DROPFILES, "WM_DROPFILES_FUNC")
GUISetState(@SW_SHOW)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE, $hExit
            Exit
        Case $GUI_EVENT_DROPPED
            For $i = 0 To UBound($gaDropFiles) - 1
                ConsoleWrite($gaDropFiles[$i] & @CR)
            Next
    EndSwitch
WEnd

Func WM_DROPFILES_FUNC($hWnd, $msgID, $wParam, $lParam)
    Local $nSize, $pFileName
    Local $nAmt = DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", 0xFFFFFFFF, "ptr", 0, "int", 255)
    For $i = 0 To $nAmt[0] - 1
        $nSize = DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", $i, "ptr", 0, "int", 0)
        $nSize = $nSize[0] + 1
        $pFileName = DllStructCreate("char[" & $nSize & "]")
        DllCall("shell32.dll", "int", "DragQueryFile", "hwnd", $wParam, "int", $i, "ptr", DllStructGetPtr($pFileName), "int", $nSize)
        ReDim $gaDropFiles[$i+1]
        $gaDropFiles[$i] = DllStructGetData($pFileName, 1)
        $pFileName = 0
    Next
EndFunc

Hi!

Edited by Nessie

My UDF: NetInfo UDF Play with your network, check your download/upload speed and much more! YTAPI Easy to use YouTube API, now you can easy retrive all needed info from a video. NavInfo Check if a specific browser is installed and retrive other usefull information. YWeather Easy to use Yahoo Weather API, now you can easily retrive details about the weather in a specific region. No-IP UDF Easily update your no-ip hostname(s).

My Script: Wallpaper Changer Change you wallpaper dinamically, you can also download your wallpaper from your website and share it with all!   My Snippet: _ImageSaveToBMPConvert an image to bmp format. _SciteGOTO Open a file in SciTE at specific fileline. _FileToHex Show the hex code of a specified file

Share this post


Link to post
Share on other sites
guinness

If you have WinAPIEx, I would do it like this.

#include <Constants.au3>
#include <GUIConstantsEx.au3>
#include <WinAPIEx.au3>
#include <WindowsConstants.au3>

Global $__aGUIDropFiles = 0, $__hGUI = 0

Example()

Func Example()
    $__hGUI = GUICreate('WM_DROPFILES', 400, 200, Default, Default, Default, $WS_EX_ACCEPTFILES)

    Local Const $iDrop = GUICtrlCreateLabel('', 0, 0, 400, 200)
    GUICtrlSetBkColor($iDrop, $GUI_BKCOLOR_TRANSPARENT)
    GUICtrlSetState($iDrop, $GUI_DROPACCEPTED)

    GUISetState(@SW_SHOW, $__hGUI)
    GUIRegisterMsg($WM_DROPFILES, 'WM_DROPFILES')

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $GUI_EVENT_DROPPED
                For $i = 1 To $__aGUIDropFiles[0]
                    MsgBox($MB_SYSTEMMODAL, '', $__aGUIDropFiles[$i])
                Next

        EndSwitch
    WEnd

    GUIDelete($__hGUI)
EndFunc   ;==>Example

Func WM_DROPFILES($hWnd, $iMsg, $wParam, $lParam)
    #forceref $hWnd, $lParam
    Switch $iMsg
        Case $WM_DROPFILES
            Local Const $aReturn = _WinAPI_DragQueryFileEx($wParam)
            If UBound($aReturn) Then
                $__aGUIDropFiles = $aReturn
            Else
                Local Const $aError[1] = [0]
                $__aGUIDropFiles = $aError
            EndIf
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_DROPFILES
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
PhoenixXL

For Single File Drag-Drop support

the following would be a simple approach

#include <GuiEdit.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Example()

Func Example()
$__hGUI = GUICreate('File Drag - Single Support', 400, 150, Default, Default, Default, $WS_EX_ACCEPTFILES)

GUICtrlCreateLabel("Path of the File", 10, 10)
Local Const $iDrop = GUICtrlCreateInput('', 10, 25, 380, 20, 0)
GUICtrlSetState($iDrop, $GUI_DROPACCEPTED)

GUICtrlCreateLabel("FileName (handled by default)", 10, 50)
Local Const $iFileName = GUICtrlCreateInput('', 10, 65, 380, 20, $ES_READONLY)
GUISetState(@SW_SHOW, $__hGUI)

While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
ExitLoop

Case $GUI_EVENT_DROPPED
GUICtrlSetData($iDrop, @GUI_DragFile)
_GUICtrlEdit_SetText($iFileName, StringRegExpReplace(@GUI_DragFile, '.*\\', ''))
EndSwitch
WEnd

GUIDelete($__hGUI)
EndFunc   ;==>Example
Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites
PhoenixXL

This script would work for multiple files

[WM_DROPFILES is taken from Guinness's code]

Here it is

#include <GUIEdit.au3>
#include <GUIConstantsEx.au3>
#include <WinAPIEx.au3>
#include <WindowsConstants.au3>
#include <Array.au3>

Global $__aGUIDropFiles = 0, $iDrop = 0, $iFileName = 0

Example()

Func Example()
$__hGUI = GUICreate('WM_DROPFILES', 400, 200, Default, Default, Default, $WS_EX_ACCEPTFILES)

GUICtrlCreateLabel("Path of the File", 10, 10)
$iDrop = GUICtrlCreateEdit('', 10, 25, 380, 50, $WS_VSCROLL)
GUICtrlSetState($iDrop, $GUI_DROPACCEPTED)

GUICtrlCreateLabel("FileName (handled by default)", 10, 85)
$iFileName = GUICtrlCreateEdit('', 10, 100, 380, 50, $ES_READONLY)

GUISetState(@SW_SHOW, $__hGUI)
GUIRegisterMsg($WM_DROPFILES, 'WM_DROPFILES')
GUIRegisterMsg($WM_COMMAND, 'WM_COMMAND')

While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
ExitLoop

Case $GUI_EVENT_DROPPED
GUICtrlSetData($iDrop, _ArrayToString($__aGUIDropFiles, @CRLF, 1))
SetFileNames()
EndSwitch
WEnd

GUIDelete($__hGUI)
EndFunc   ;==>Example

Func WM_DROPFILES($hWnd, $iMsg, $wParam, $lParam)
#forceref $hWnd, $lParam
Local Const $aReturn = _WinAPI_DragQueryFileEx($wParam)
If UBound($aReturn) Then
$__aGUIDropFiles = $aReturn
Else
Local Const $aError[1] = [0]
$__aGUIDropFiles = $aError
EndIf
Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_DROPFILES

Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
#forceref $hWnd, $lParam
$iControl = _WinAPI_LoWord($wParam)
If $iControl <> $iDrop Then Return $GUI_RUNDEFMSG

Local $iNotification = _WinAPI_HiWord($wParam)
Switch $iNotification
Case $EN_KILLFOCUS
SetFileNames()
EndSwitch

Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_COMMAND

Func SetFileNames()
Local $sRead = GUICtrlRead($iDrop)
Local $asFileNames = StringRegExp($sRead, "(?m)^.*\\(.*)$", 3)

If Not IsArray($asFileNames) Then Return 0

_GUICtrlEdit_SetText($iFileName, _ArrayToString($asFileNames, @CRLF))
Return 1
EndFunc   ;==>SetFileNames
Ask if you have any queries

Regards :)


My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites
Myicq

Hopefully this does not count as Necroposting (what is the limit anyway ?).

I have a question related to this, especially the last example from PhoenixXL: how can I find out if the dragged is a directory ?

I know I can put a parameter on _winAPI_DragQueryFileEx but I would like to handle directories as well, just differently.


I am just a hobby programmer, and nothing great to publish right now.

Share this post


Link to post
Share on other sites
guinness

Hopefully this does not count as Necroposting (what is the limit anyway ?).

 

I have a question related to this, especially the last example from PhoenixXL: how can I find out if the dragged is a directory ?

I know I can put a parameter on _winAPI_DragQueryFileEx but I would like to handle directories as well, just differently.

It does.

The answer to your question is FileGetAttrib(), something you should know already.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×