Why won't hotkeys work on certain desktop applications? - autoit

Ok so I have used Autoit, python, and Powertoys to create shortcuts but when I try to use the hotkey on a certain desktop application (Its a cash register app) it will not respond, the script is still working because I go back to notepad and the hot key still works. Does anyone know why the app will not respond to simulated keystrokes?
HotKeySet ( '{Insert}' ,'Func1')
HotKeySet ( 'x' ,'Func2')
While 1
Sleep(50)
WEnd
Func Func1()
Send("b")
EndFunc
Func Func2()
Exit
EndFunc
The hot key works fine on notepad and the internet but I when I click the Cash Register Application the Hot keys do not work, the script is still running because if I go back to notepad the hotkeys still work.

What I would start off by doing is checking if the hot key is set or blocked by the existing application. Always check for error.
Func Func1()
If #HotKeyPressed = 0 Then Return MsgBox(0, "Hotkeyset Error", "Hotkey " & #HotKeyPressed & " already set by another task.")
EndFunc

Related

Using apple script to press the return key when prompted to connect to server

Currently this is my delima. Once in a while a build agent will reboot. It needs to always stay connected to share on one of our servers. The idea was to tell finder to mount the volume, wait 2 seconds, and then press enter...since the user name and pssword are both part of the address when I enter it such as SMB://username:password#Server1/DFS it pops up the pasword dialog fully populated but I can't get applescript to recognize it, then press either connect or the return to say "Yes" login witht hat name and don't prompt me.
it worked fine when connecting at home to a synology device but it's not working when connecting to a server in the office.
tell application "Finder" to mount volume "SMB://username:password#Server1/DFS"
delay 2
tell application "System Events" to keystroke "return" -- key code 36
Any help for this seemingly simple step would be greatly apprecited.
I have looked ove the forums and found variou stratagies but they all relate to an application like Firefox or some other script aware app. I just need it to press enter when the password dialog comes up.
First of all the Finder is not needed to mount a volume, you can delete the tell block.
Secondly, if username and password are passed the volume is supposed to mount without a dialog. Maybe you could find the reason why it doesn't.
Nevertheless the password dialog belongs to the process SecurityAgent, you have to use (ugly) GUI scripting to press the button:
tell application "System Events"
repeat until exists process "SecurityAgent"
delay 0.5
end repeat
tell window 1 of process "SecurityAgent"
click button 2
end tell
end tell
The script waits until the window appeared, this is much more reliable than an hard-coded delay.
Looks like a possible XY Problem as I would expect a solution such as https://apple.stackexchange.com/a/698/204318 to work for you to directly mount the share:
mount -t smbfs //username:password#MACHINENAME/SHARENAME /SomeLocalFolderOfChoice
However, if you are really required to interact with the dialog, and as you asked about it, take a look at this tutorial (written in Python) for scripting up something:
detect missing connection
attempt connection
capture screen periodically
look for dialog box, else loop
error after a few seconds of failure
if dialog is detected, interact with it
input username and password
wait, then press return
check if connection worked after a small delay
success or failure
This type of strategy is very powerful for interacting with all sorts of different dialogs you may encounter and should be possible in AppleScript if you are much more familiar with it (or another scripting language).
If you are open to non-AppleScript solutions, then you might consider Keyboard Maestro, one of the best Mac automation tools available.
You said:
it pops up the pasword dialog fully populated but I can't get
applescript to recognize it, then press either connect or the return
to say "Yes" login witht hat name and don't prompt me.
You could probably do this very easily using Keyboard Maestro. Here's an example of the KM Actions to accomplish this.
If you'd like help with KM, please visit the forum at:
https://forum.keyboardmaestro.com/
I'm a big AppleScript/JXA user, but I often find it easier/quicker to use KM for many automation tasks. Of course, KM Macros can execute AppleScript, JXA, Shell Scripts, and other scripts easily.
You can try a full version of KM for free for 30 days.

HKWorkoutSession isn't keeping app at front of Apple Watch

It has been stated that an app running a HKWorkoutSession will have special privileges over other watchOS 2 apps, so when a user looks at their Apple Watch, it will go to the view showing running a workout rather than the watch face.
Currently, on both my device and simulator, this is not the case. If I start a HKWorkoutSession and then leave for 5 minutes and then interact with either the Apple Watch, or the Watch Simulator, it presents the watch face.
If I then open my app, it appears to have been frozen, rather than terminated (which is what I imagine happens to other apps). As the UI will update when I need receive a response in my query.updateHandler. Also if I set it to provide haptic feedback every time my query.updateHandler receives a new HKQuantitySample it will do so, so the app must be running in the background in some form.
Has anyone else noticed this behaviour, and am I doing anything wrong, or expecting something I shouldn't?
Here is how I start my HKWorkoutSession:
self.workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.Other, locationType: HKWorkoutSessionLocationType.Indoor)
self.healthStore.startWorkoutSession(self.workoutSession) {
success, error in
if error != nil {
print("startWorkoutSession \(error)\n")
self.printLabel.setText("startWorkoutSession \(error)")
self.printLabel.setTextColor(UIColor.redColor())
}
We're seeing that too, for the moment we've made sure 'opens last activity' is configured.
When the UI is active we start a dispatch_timer to request and process data in 1 second intervals.
Make sure you do any significant processing using the NSUserProcessInfo method though and pause the dispatch_timers whenever you are no longer active. You'll get crashes otherwise.

Search for a folder using applescript

I am trying to make a folder to go on a server, that people can add photos to and then the script sends them to the correct place, however I'm having trouble with the search part.
As you can see below in my code, the part where it finds where to send the folder to is commented out, because I have no idea what the syntax is for it.
Any help would be greatly appreciated.
global theWatchedFolder
set theWatchedFolder to choose folder
on idle
tell application "Finder"
set theDetectedItems to every item of theWatchedFolder
repeat with aDetectedItem in theDetectedItems
set jobNumber to display dialog "Please enter the job number for this photo." buttons {"Submit", "Cancel"}
display dialog "File detected: " & jobNumber
--tell finder
-- search for jobNumber in (path to desktop)
--set jobFolder to top search result
--end tell
--set colourFolder to jobfolder & /colour
move aDetectedItem to the desktop --move to colourFolder
end repeat
end tell
if theDetectedItems is not {} then
activate
display dialog "test move complete"
end if
return 1
end idle
Also, I am concerned that if this script is on the server, watching a folder on the server, then it won't create a pop-up for anyone who adds a file to the folder on the server. Hopefully I am wrong but if someone could confirm this one way or the other then that would be awesome. Thanks :)
I can confirm your biggest fear. The display dialog is shown in the Finder who is targeted. You'll always address the Finder on the same machine that is running your script, unless your using remote events. If the script is running on the server, the dialog will appear in the Finder running on the server.
I have also a side note that you continuously keep running AppleScript using an idle handler to check for any updates in a particular folder. Did you know that AppleScript has memory leaks as an stay open application? It's software you don't want to run constantly on a server. It's better to start a new AppleScirpt in a new process once in a while (I prefer something like every hour) and quit the current running one. You can still use the idle handler but if the idle handler runs every 10 seconds I would quit this script and start a new one after 600 loops.
Then back to your search. Finder doesn't have a search command. Since Mac OS X Tiger Apple introduced spotlight, a meta database for finding different kind of data (files, bundles, mails, etc). However spotlight has never been scriptable but for AppleScript only accessible on the command line using mdls, mdfind and mdutil. To execute commands on the command line we use the do shell script command in AppleScript or do script command for scripting the Terminal.app. Here an example of how to use with a do shell script command
set theFolder to choose folder
set searchKey to "the*" --use * as wild card
findMetaDataInFolderByName(theFolder, searchKey)
on findMetaDataInFolderByName(HFSPath, searchKey)
set options to " -onlyin " & quoted form of POSIX path of HFSPath
set options to options & " \"kMDItemFSName == " & quoted form of searchKey & "\""
return paragraphs of (do shell script "mdfind " & options)
end findMetaDataInFolderByName
note: because we're working in the shell the paths returned are posix path which can be used anywhere by prefixing the path with posix file
But, you have mentioned that the search has to be invoked on a server. Normally when your have a server properly installed the shares are outside the application and user home folder. These folders are by default only indexed by spotlight so spotlight needs to index on the fly. In other words it's very slow compared to normal spotlight searches with are done in less than a second. So I would suggest another version of the same script as above but using find. Find will simply walk recursively to the given directory and print every match.
set theFolder to choose folder
set searchKey to "the*" --use * as wild card
findFilesInFolderByName(theFolder, searchKey)
on findFilesInFolderByName(HFSPath, searchKey)
--the HFSPath can't have a trailing "/"
set UFSPath to POSIX path of HFSPath
if UFSPath ends with "/" and UFSPath is not "/" then set UFSPath to text 1 thru -2 of UFSPath
set options to space & quoted form of UFSPath
set options to options & " -iname " & quoted form of (searchKey) --iname is case insensitive file name match
paragraphs of (do shell script "find " & options & " -print 2>/dev/null ; exit 0") --pipe error to /dev/null to exclude permission denied messages
end findFilesInFolderByName
note: A side effect is because find will try every file while meta data search works different you'll probably find more files now because folders are included in the search as well. Just like findMetaDataInFolderByName(), findFilesInFolderByName() will return posix paths.

Stop Processing Of ASP.Net Web Form on Opening an Exe

In my ASP.net application, i have to open a EXE on click of button. When the EXE is open, User should not be allowed to perform any action on the web form, i.e. the exe should behave like a modal popup. I am using the current code to open and return value from EXE.
Dim p As Process
p = Process.Start("D:\VS2010Projects\SignatureCaptureWindows\bin\Debug\SignatureCaptureWindows.exe")
p.WaitForExit()
If (Not p.ExitCode.Equals(0)) Then
Response.Write("Image Successfully saved in Database with ID = " + p.ExitCode.ToString())
DisplaySavedImage(p.ExitCode)
End If
The Exe is opening fine and returning the correct value. However, the user is able to perform action on the web form when the exe is open...
What will be the best way to handle such a scenario ??
Its impossible to do the way you won it. From the moment the user send a submit, or try to open the page, and on code behind you run this exe, then user is wait for the results - in this time you can not make the user to not do anything else - you can not lock the browser, user can close it, reload it, open again the same page, etc.
What you can do is to lock this process using Mutex and not allow to run again if all ready run it.
Mutex on msdn with example : http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

Haskell System.Timeout.timeout crashing when called from certain function

I'm scraping some data from the frontpages of a list of website domains. Some of them are not answering, or are very slow, causing the scraper to halt.
I wanted to solve this by using a timeout. The various HTTP libraries available don't seem to support that, but System.Timeout.timeout seems to do what I need.
Indeed, it seems to work fine when I test the scraping function, but it crashes as soon as I run the enclosing function: (Sorry for bad/ugly code. I'm learning.)
fetchPage domain =
-- Try to read the file from disk.
catch
(System.IO.Strict.readFile $ "page cache/" ++ domain)
(\e -> downloadAndCachePage domain)
downloadAndCachePage domain =
catch
(do
-- Failed, so try to download it.
-- This craches when called by fetchPage, but works fine when called from directly.
maybePage <- timeout 5000000 (simpleHTTP (getRequest ("http://www." ++ domain)) >>= getResponseBody)
let page = fromMaybe "" maybePage
-- This mostly works, but wont timeout if the domain is slow. (lswb.com.cn)
-- page <- (simpleHTTP (getRequest ("http://www." ++ domain)) >>= getResponseBody)
-- Cache it.
writeFile ("page cache/" ++ domain) page
return page)
(\e -> catch
(do
-- Failed, so just fuggeddaboudit.
writeFile ("page cache/" ++ domain) ""
return "")
(\e -> return "")) -- Failed BIG, so just don't give a crap.
downloadAndCachePage works fine with the timeout, when called from the repl, but fetchPage crashes. If I remove the timeout from downloadAndCachePage, fetchPage will work.
Anyone who can explain this, or know an alternative solution?
Your catch handler in fetchPage looks wrong -- it seems you're trying to read a file, and on file not found exception are directly calling into your http function from the exception handler. Don't do this. For complicated reasons, as I recall, code in exception handlers doesn't always behave like normal code -- particularly when it attempts to handle exceptions itself. And indeed, under the covers, timeout uses asynchronous exceptions to kill threads.
In general, you should put as little code as possible in exception handlers, and especially not put code that tries to handle further exceptions (although it is generally fine to reraise a handled exception to "pass it on" [as with bracket]).
That said, even if you're not doing the right thing, a crash (if it is a segfault type crash as opposed to a <<loop>> type crash), even from weird code, is nearly always wrong behavior from GHC, and if you're on GHC 7 then you should consider reporting this.

Resources