Get path of active window's directory

Get help with using AutoHotkey and its commands and hotkeys
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Get path of active window's directory

21 Oct 2017, 03:24

Hi !

I'm new to AutoHotKey and loving it :-)
I'd like to write a script that allows my to open the active window's directory with a HotKey. (Ex: I'm on Excel working on C:\Users\Thomas\MyPath\MyDoc.xlsx, I hit the HotKey and it opens C:\Users\Thomas\MyPath in the explorer).

I know how to open the explorer once I get the path

Code: [Select all] [Download] GeSHi © Codebox Plus

^F2::Run, explorer.exe %MyPath% 


But how do I get the path of active window's directory?

Thanks a lot for your help!!
Cheers,
Thomas
Helgef
Posts: 2402
Joined: 17 Jul 2016, 01:02
Contact:

Re: Get path of active window's directory

21 Oct 2017, 03:47

See winGet and winActive, eg,

Code: [Select all] [Download] GeSHi © Codebox Plus

f1::
WinGet, activePath, ProcessPath, % "ahk_id" winActive("A") ; activePath is the output variable and can be named anything you like, ProcessPath is a fixed parameter, specifying the action of the winget command.
msgbox % activePath
return

Also see, winTitle and force an expression (single: %).
Cheers.
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

21 Oct 2017, 12:16

It sounds like you want the path (or rather dir) of the open file in Excel:

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus



Various Explorer functions:
Explorer window interaction (folder windows/Desktop, file/folder enumeration/selection/navigation/creation) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=35041
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

21 Oct 2017, 13:00

Thanks a lot for your help Helgef and jeeswg !

@Helgef: your code gets me the path of the process of the active window. I'd like to get the path of the folder of the file I'm working with.

@jeeswg : yep, that's the idea, except that I want to get this for any kind of document, not only Excel : all Office Suite, IDEs, photo editing soft, etc...

Any clues @all?

Cheers!
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

21 Oct 2017, 13:15

This is a tough one, the method depends on each individual program.

- A fallback method, not 100% perfect but generally pretty reliable is to check for the name of a file in the title bar, and compare it against files in the Recent folder.
list Recent Items (My Recent Documents) (Start Menu) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=31386
- Many programs have COM like Excel, so you could use a similar method to the one above.
- If the application stores a list of recent files in the registry, retrieve the name from the title bar and then check for it the registry. I know that MS Paint (Windows XP) however doesn't update this list until you close it, however I believe Adobe Reader and Media Player Classic keep these lists up-to-date.
- It may be possible to retrieve the file name from the address space of the application, although you could get some false positives. Either by searching binary data, or by checking a consistent memory address.
notepad get/set path (get/set text file path) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=30050
- Some programs may offer support using PostMessage/SendMessage.
- Sometimes you can set a program to show the full path of a file in the title bar.
- If you try to close Notepad with unsaved changes, the path is listed in the warning message.
- You can go to the Open/Save As prompts, and retrieve the directory from there.
get full paths of selected files on Desktop and Common File Dialogs - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=5&t=31135

Sometimes programs display a file name in a way that is based on whether extensions are set to hidden/shown, a file's display name. You can loop through files in a folder and use GetFileTitle to get that display name, and then list any matching files.

I think this is an area where generally programs need to do better.

[EDIT:] Another thing to mention is sometimes you can get a path from the command line, however, the program may have since opened a different file, so this is not necessarily reliable.
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

24 Oct 2017, 11:29

Thanks jeeswg for your answer!
It's a shame that no clean and simple solution exists, I've looked a lot and find nothing indeed...

In the ideas you list, I thought the first one (match for Recent items) would be the best to try.
So I tried your script. Problem is that the lists of "Recent documents" I get from your script is not up to date. I found out that C:\Users\%user%\AppData\Roaming\Microsoft\Windows\Recent has a more up to date list of recent document. So I based my script on this to implement your idea.

I've got something that partially works but is not perfect and would love some help if possible!
Here's what I got:

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus



In its principle it does work, but errors occur due to the regex: some I don't understand, and I see how in some cases I could have problems:
- Sometimes the regex doesn't seem to match anything even though my document IS listed in the Recent Items folder, and SHOULD match
- Due to how I split the file name to get the regex to work (

Code: [Select all] [Download] GeSHi © Codebox Plus

StringSplit, word_array, Title,"-"
), a problem could occur if 2 documents were opened recently and happen to have their namefile begining in the same manner.

Help on this splitter + regex would be welcome, because I think the script will work fine after that!
Thanks!!

NB : I'm a total newbie programmer, don't hesitate to give any other advice!
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

24 Oct 2017, 11:58

Here's a script to get the display name from Notepad's window title and look it up in the Recent folder.

If the window title always has the name plus extension, or the full path, that would make the script slightly easier to write, you wouldn't need GetFileTitle to get the display name.

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus

dilligence
Posts: 22
Joined: 25 Aug 2017, 14:31
Location: The Netherlands
Contact:

Re: Get path of active window's directory

24 Oct 2017, 20:29

Helgef,

Cool script!
Instead of the MSGbox, is it possible to copy the application path to the clipboard?
dilligence
Posts: 22
Joined: 25 Aug 2017, 14:31
Location: The Netherlands
Contact:

Re: Get path of active window's directory

24 Oct 2017, 20:39

Nevermind, already got it:

Code: [Select all] [Download] (Untitled.ahk)GeSHi © Codebox Plus

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
f1::
WinGet, activePath, ProcessPath, % "ahk_id" winActive("A") ; activePath is the output variable and can be named anything you like, ProcessPath is a fixed parameter, specifying the action of the winget command.
Clipboard := activePath
return
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

25 Oct 2017, 03:27

Thank you jeeswg!!
I don't understand every detail of your script, but I think I get mosts of the idea.
However, it works only with Notepad files, which is logical I guess given the lines

Code: [Select all] [Download] GeSHi © Codebox Plus

WinGetTitle, vWinTitle, ahk_class Notepad
vDName1 := RegExReplace(vWinTitle, " - Notepad$")


So I know how to make it work for any program individually, for instance for Excel I can do:

Code: [Select all] [Download] GeSHi © Codebox Plus

WinGetTitle, vWinTitle, A
vDName1 := RegExReplace(vWinTitle, " - Excel$")


For Word I can do:

Code: [Select all] [Download] GeSHi © Codebox Plus

WinGetTitle, vWinTitle, A
vDName1 := RegExReplace(vWinTitle, " - Word$")


But is there a way to make the script work in any program?
Basically I would need to have a %specific_program_end_of_window_title% variable, in order to write:

Code: [Select all] [Download] GeSHi © Codebox Plus

WinGetTitle, vWinTitle, A
vDName1 := RegExReplace(vWinTitle, %specific_program_end_of_window_title%)


I see how I could use an sequence of if statements to match ahk_class with the name of program in window title (or an array), but that doesn't seen very clean to me.

Any smarter way?
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

25 Oct 2017, 03:55

Really SubStr can be used rather than RegExReplace.

Code: [Select all] [Download] GeSHi © Codebox Plus

q::
oArray := {Notepad:" - Notepad", WordPadClass:" - WordPad"}
WinGetClass, vWinClass, A
WinGetTitle, vWinTitle, A
if oArray.HasKey(vWinClass)
MsgBox, % "[" SubStr(vWinTitle, 1, -StrLen(oArray[vWinClass])) "]"
return

I believe that most programs do 'Title - Program', e.g. Adobe Reader and WinDjView, although quite likely a few will vary. On Excel 2007 it uses 'Microsoft Excel - Book1', i.e. program first which is unusual.

How many programs are you thinking about in total. If you list some/all of them, then maybe some of them have more direct ways than using the Recent folder.
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

25 Oct 2017, 08:11

Hey,

So I tried to implement your solution with an array and SubStr in the full code, and it doesn't work. Should be close but there must be a small problem that I don't get. Here's my code:

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus

User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

25 Oct 2017, 13:27

I don't know what that 'a' is doing there:
if oArray.HasKey(vWinClass)a{

This includes square brackets, which were only there to check that there was no leading/trailing whitespace:
vDName1 := "[" SubStr(vWinTitle, 1, -StrLen(oArray[vWinClass])) "]"
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

26 Oct 2017, 04:48

Hi jeeswg!
Indeed the 'a' was a typo.

However I don't understand your second point, and my script still doesn't work after having deleted the 'a'
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

26 Oct 2017, 05:41

The vDName1 line is adding characters, square brackets, to the string, e.g. giving '[MyFile.txt]' instead of 'MyFile.txt'.
GEV
Posts: 621
Joined: 25 Feb 2014, 00:50

Re: Get path of active window's directory

26 Oct 2017, 11:49

Try also

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus

User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

27 Oct 2017, 02:31

Some registry locations for retrieving paths:

WordPad (location confirmed on Windows XP and Windows 7):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List
MS Paint (location confirmed on Windows XP and Windows 7):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List

Note: WordPad and MS Paint only set the registry Recent File List when they are closed. They set the contents of the recent file list to be the same as that which appears in the File menu. Tested on Windows XP and Windows 7.

Media Player Classic:
HKEY_CURRENT_USER\Software\MPC-HC\MPC-HC\Recent File List
Adobe Reader:
HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\11.0\AVGeneral\cRecentFiles
WinDjView:
HKEY_CURRENT_USER\Software\Andrew Zhezherun\WinDjView\Recent File List

==================================================

@GEV:
Unfortunately I couldn't get this to work, even when Excel was the active window.

Code: [Select all] [Download] GeSHi © Codebox Plus

; Excel
If WinActive("ahk_exe excel.exe")
{
oExcel := ComObjActive("Excel.Application")
path := oExcel.ActiveWorkbook.FullName
}

Also I believe issues relating to getting the active workbook, led to functions like 'Excel_Get' and 'Word_Get' mentioned here:
excel and com? - Page 2 - Ask for Help - AutoHotkey Community
https://autohotkey.com/board/topic/73940-excel-and-com/page-2
I'm not sure what the latest recommended functions for these are.

Re. Notepad/WordPad/IrfanView, that code retrieves the command line, however, that gives the first (or no) file opened, rather than the most recently opened file.
Last edited by jeeswg on 05 Nov 2017, 15:15, edited 1 time in total.
carthagod
Posts: 16
Joined: 20 Oct 2017, 06:52

Re: Get path of active window's directory

31 Oct 2017, 09:18

Hey jeeswg!

So sorry for my late reply, I didn't receive any email notifications from those posts...

Thanks for your answer to my question, I've finally got something that works, thank you so much!!

Here's my script:

Code: [Select all] [Expand] [Download] GeSHi © Codebox Plus



* Probably not the most stable nore beautiful piece of code, but it works in most cases and that all that matters to me here :-)
* Works for: Powerpoint, Word, Excel, Notepad, Adobe pdf Reader, SciTEWindow
* Doesn't work for: PHP Storm and Notepad++ (in both cases because of name of window, possible workarounds which I might do someday if really needed)
* Known limitations: for SciAutoHotkey, works only with one file open, if several files opens the name of window changes.
* Go to know: sometimes Office files are in "[Compatibility Mode]", which changes the name of the window, hence lines 20 to 23 to deal with that. (If you have an answer to my comment on line 22 regarding StrLen("[Compatibility mode]") which doesn't work, I'd be curious).


GEV thanks a lot for your contribution: it works like a charm as well! Doesn't work yet with Powerpoint nore PHPstorm but that could be added, and it does work with Notepad++ which is cool :-)

You guys ROCK, this is awesome :-)

Such a useful little trick don't you think?
Everytime you have to attach a document your working on, F3 and tada, ready to drag and drop ! :dance:
User avatar
jeeswg
Posts: 2659
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Get path of active window's directory

31 Oct 2017, 09:34

That looks good.

Btw normally files are shown as NameNoExt.Ext or NameNoExt, depending on whether extensions are set to shown or hidden.
Potentially some programs will ignore that and always show or hide the extension.

By doing a Google image search, the template appears to be:
'MyFile.xls [Compatibility Mode] - Microsoft Excel'

So the number of characters to be removed:
39 chars: ' [Compatibility Mode] - Microsoft Excel'
18 chars: ' - Microsoft Excel'
21 chars: ' [Compatibility Mode]'

Some possibilities:

Code: [Select all] [Download] GeSHi © Codebox Plus

if (SubStr(vDName1, StrLen(vDName1)-21+1) = " [Compatibility Mode]")
if InStr(vDName1, " [Compatibility Mode]")
if RegExMatch(vDName1, " [Compatibility Mode]$")

vDName1 := SubStr(vWinTitle, 1, -21)
vDName1 := SubStr(vWinTitle, 1, -StrLen(" [Compatibility Mode]"))


I'm not sure where the number 28 comes from.

[EDIT:] Btw I thought I'd mention this, it might not matter too much, but this might be better because it will get files via the registry, in an order based on how recently they were opened. Note: there is the slight possibility of two different files with the same display name being present in the Recent list whether you get it from the registry or from the folder.

list Recent Items (My Recent Documents) (Start Menu) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=31386
Helgef
Posts: 2402
Joined: 17 Jul 2016, 01:02
Contact:

Re: Get path of active window's directory

31 Oct 2017, 10:35

carthagod wrote: Doesn't work for: Notepad++

If you go to Settings -> Preferences -> MISC. There is a checkbox which says Show only filename in title bar, untick it to get the complete path to the open file. I use that to open AHK scripts with different versions of AHK.

Cheers.

Return to “Ask For Help”

Who is online

Users browsing this forum: adamas, Nightwolf85, Odlanir, scriptor2016 and 56 guests