How to exit program using autohotkey? - google-chrome

I am using autohotkey to do some automate process.
I need help with closing chrome.exe
I tried
Process, Close, chrome.exe
; or
Run taskkill /im chrome.exe
but it give me chrome crashed error when I start it again.
Thanks

Use WinClose to send a close message to the window, rather than killing the process:
SetTitleMatchMode 2
WinClose Google Chrome

mihai's helpful answer works well if a single Chrome window (typically containing multiple tabs) is open.
However, more work is needed if you want to close all open Chrome windows:
; Get all hWnds (window IDs) created by chrome.exe processes.
WinGet hWnds, List, ahk_exe chrome.exe
; Loop over all hWnds and close them.
Loop, %hWnds%
{
hWnd := % hWnds%A_Index% ; get next hWnd
WinClose, ahk_id %hWnd%
}
Also note that the WinClose documentation calls using WinClose's use of the WM_CLOSE message "somewhat forceful" and suggests the following PostMessage alternative, which mimics the user action of pressing Alt-F4 or using the Window menu's Close item:
; Get all hWnds (window IDs) created by chrome.exe processes.
WinGet hWnds, List, ahk_exe chrome.exe
; Loop over all hWnds and close them.
Loop, %hWnds%
{
hWnd := % hWnds%A_Index% ; get next hWnd
PostMessage, 0x112, 0xF060,,, ahk_id %hWnd%
}

Here is a function for 'soft closing' specific processes:
CloseAllInstances( exename )
{
WinGet LhWnd, List, % "ahk_exe " exename
Loop, %LhWnd%
PostMessage, 0x112, 0xF060,,, % "ahk_id " LhWnd%A_Index%
}
So you simply need to call the following line to close all chrome instances:
CloseAllInstances( "chrome.exe" )

Related

Trigger Brave "Search Tabs" feature from Autohotkey

I would like to be able to trigger "Search Tabs" from Autohotkey, since I have lots of opened tabs this would help me quickly find the tab I am looking for, I know I might be able to loop through all tabs by scripting this, but that's not what I want.
This is what I've done
!+a::
WinActivate, Brave
Sleep, 100
Send, {Ctrl}{Shift}a
Return
If I change Send, {Ctrl}{Shift}a with Send, {Ctrl}t is correctly opens a tab, so the problem must be either some error in my {Ctrl}{Shift}a configuration or that Brave is somehow not reacting.
The most appropriate way to activate a specific window and send keystrokes to it is as follows:
!+a::
SetTitleMatchMode, 2 ; if you want to use it only in this hotkey
IfWinNotExist, Brave
{
MsgBox, Cannot find Brave
Return ; end of the hotkey's code
}
; otherwise:
WinActivate, Brave
WinWaitActive, Brave, ,2 ; wait 2 seconds maximally until the specified window is active
If (ErrorLevel) ; if the command timed out
{
MsgBox, Cannot activate Brave
Return
}
; otherwise:
; Sleep 300 ; needed in some programs that may not react immediately after activated
Send, ^+a
Return
Otherwise the script can send the keystrokes to another window.
For not repeating the whole code in every hotkey you can create a function:
!+b::
SetTitleMatchMode, 2
Activate("Brave", 2)
; Sleep 300
Send, ^+a
Return
Activate(title, seconds_to_wait){
IfWinNotExist, % title
{
MsgBox % "Cannot find """ . title . """."
Return
}
; otherwise:
WinActivate, % title
WinWaitActive, % title, ,% seconds_to_wait
If (ErrorLevel)
{
MsgBox % "Cannot activate """ . title . """."
Return
}
}

Loop to check if the chrome is still working using Batch language CMD

I have a certain task to do which requires some chrome profiles to stay launched and never close them, the problem is sometimes the chrome app may get crashed causing the closing of all the profiles I'm opening I calculated the duration is about 4 days, I thought about making a loop using cmd that checks if the chrome process is still launched or not and if not it opens the profiles again, like in Linux we can open a certain process using Terminal and then we can't close the process unless we closed the terminal console, I'm new at Batch language here what I did:
#echo off
SET /A "index = 1"
SET /A "count = 5"
:while
if %index% leq %count% (
echo Checking if the chrome is still working...
rem a command to stay checking the process
rem if no
rem start "name of the shortcut of the profile"
SET /A "index = index + 1"
goto :while
)
To be honest I don't know what am I doing.

Start Chrome Minimized?

rundll32 shell32.dll,ShellExec_RunDLL "C:\...\shortcut.lnk"
rundll32 shell32.dll,ShellExec_RunDLL "C:\...\shortcut2.lnk"
That's what I've got so far running inside a batch. It starts Chrome just fine, but I want it to start minimized as I only want a page to autorun and then Chrome be closed later automatically. I don't ever want the window to be anything other than minimized.
So far I've tried /min in every location of this command that I could and none have worked. The only position where it does anything is before the directory and it seems to run the Chrome process and then kills it immediately after. Putting --no-startup-window as a parameter in the shortcut also reacts the same way.
I've tried a few other things as well like setting the shortcuts to "minimized" in the window mode, but nothing has worked so far. I could really use some help with this as I'm pretty much stuck. The solution could either be a command for a batch executable or something having to do with the actual shortcut file.
Any help would be greatly appreciated. I'd hate to have to manually minimize these two windows every day.
Here are the two shortcuts and batch file if you want to mess with them.
https://drive.google.com/uc?export=download&id=0B_KZqubEguX6N04xOVZfWVVlQUE
If you just need to run Chrome from a bat file with non full screen mode you can try to use these parameters:
--window-position=0,0 --window-size=1,1
While thinking about a solution within a batch file and coming to the conclusion that there isn't a better solution, than also described above, I've written this quick and dirty piece of code and compiled it in case that you don't have a compiler:
(You will find it also as a snippet on Gist)
Module Module1
Sub Main(ByVal Args() As String)
Try
If Args.Length = 2 Then
Dim fileName As String = Args(1)
If Not String.IsNullOrEmpty(fileName) Then
If System.IO.File.Exists(fileName) Then
Dim startInfo As New ProcessStartInfo(fileName)
Select Case Args(0).ToLower()
Case "hide"
startInfo.WindowStyle = ProcessWindowStyle.Hidden
Case "minimize"
startInfo.WindowStyle = ProcessWindowStyle.Minimized
Case Else
Console.WriteLine(Args(0) & " is unknown. Showing Window.")
startInfo.WindowStyle = ProcessWindowStyle.Normal
End Select
Process.Start(startInfo)
Else
Throw New System.IO.FileNotFoundException("The file specified was not found. (""" & fileName & """)")
End If
Else
Throw New System.ArgumentOutOfRangeException("No file specified.")
End If
Else
Throw New System.Exception("Invalid count of arguments")
End If
Catch ex As Exception 'Optional: Catch ex As System.IO.FileNotFoundException
Console.Error.WriteLine("ERROR" & vbCrLf & ex.Message)
End
End Try
End Sub
End Module
Download the compiled file: RunProcess.exe.
For those who aren't familiar with vb.net or don't want to read this bad formatted thing:
You can use it the following way:
RunProcess minimize "C:\Program Files\[...]\chrome.exe"
RunProcess hide "C:\Program Files\[...]\chrome.exe"
RunProcess show "C:\Program Files\[...]\chrome.exe"
At this point it doesn't check execute paths:
RunProcess minimize "cmd.exe" wont work. You would have to use RunProcess minimize "%systemroot%\System32\cmd.exe"
EDIT:
Also have a look at this: Start-Process -WindowStyle Hidden "chrome.exe" "www.google.com"
If you do not want them to stay open for very long you could do like this
start "C:\Portable Apps\Program Files\Google Chrome\GoogleChromePortable.exe" <somelink1>
start "C:\Portable Apps\Program Files\Google Chrome\GoogleChromePortable.exe" <somelink2>
Taskkill /F /IM GoogleChromePortable.exe
or
Taskkill /F /IM chrome.exe

Creating a batch file that opens google chrome and puts input into the search box?

So I am just playing with batch files and was curious if it was possible to create a batch file that opens the google browser and without typing into the search box, a variable from my batch file gets put into the search box. Anyone know if that's possible? Thanks.
#echo off
cd c:\program files (x86)\google\application
start chrome.exe www.youtube.com
I can open the web browser, I can even change the code to store the variable, but need to know how to send that variable to the search engine. Youtube i just the website i left it at.
If you use google as search engine, try to pass the keyword like this :
#echo off
start "" chrome.exe www.google.com#q=batch
and if you want add more than a keyword just add the sign +
#echo off
start "" chrome.exe www.google.com#q=batch+vbscript+HTA
You could send raw HTTP request as follows:
start "" "c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "https://www.youtube.com/results?search_query=simon's cat"
Below is possible approach how-to make it more readable in a batch script (non-systematic approach, as e.g. site variable joins together protocol and host name). Use appropriate value of engine variable for a particular host (as it could vary for different servers):
#ECHO OFF >NUL
SETLOCAL EnableExtensions EnableDelayedExpansion
set "chromepath=c:\Program Files (x86)\Google\Chrome\Application" path to chrome
set "site=https://www.youtube.com"
set "engine=results?search_query"
set "search=simon's cat" string to search
start "" "!chromepath!\chrome.exe" "!site!/!engine!=!search!"
Delayed expansion used as any variable in above code could contain cmd poisonous characters.
If you want the simplest alternative, you can just copy the full link and paste it in:
#echo off
start chrome "youtube.com/results?search_query=funny+videos"
To open another tab, separate first address with a space and type "google.com" next to it.
If you want to open another browser like FireFox at the same time, type on a new line: start firefox "stackoverflow.com"
It'll look something like this:
#echo off
start chrome "youtube.com/results?search_query=funny+videos" "google.com"
start firefox "stackoverflow.com"
#echo off
set tmp="%*"
IF %tmp% == "" (
GOTO :query
) ELSE (
GOTO :replace
)
:replace
set url=%*
REM set url=%url: =+%
echo %url%
GOTO :search
:query
set /p url=Input search Keywords:
GOTO :search
:search
echo Search query confirmed: %*
echo Attaching to process..
tasklist /nh|findstr "chrome.exe" && start "" "chrome.exe" "? %url%"
REM tasklist /nh|findstr "chrome.exe" && start "" "chrome.exe" "www.google.com/search?q=%url%"
Here is the batch file I use for accomplishing this.
It will attach the search tab to an open process of chrome and search for %* arguments.
If you don't pass arguments, it will ask for some.
> url installing pycharm on ubuntu
There is a commented out method aswell that replaces spaces with '+', then searches with raw HTTP instead of the "? %url%" option.
Delete REM on line 12 and 25, and all of line 24 to switch
#echo off
echo Welcome to my Search Engine!
echo Type 1 Keyword to Search. Use +s instead of spaces
set/p "keyw=Keyword is "
start https://www.google.com/search?q=%keyw%&sourceid=ie7&rls=com.microsoft:en-US:IE-Address&ie=&oe=

Vim function to copy a code function to clipboard

I want to have keyboard shortcut in Vim to copy a whole function from a Powershell file to the Windows clipboard. Here is the command for it:
1) va{Vok"*y - visual mode, select {} block, visual line mode, go to selection top, include header line, yank to Windows clipboard.
But it would work only for functions without an inner {} block. Here is a valid workaround for it:
2) va{a{a{a{a{a{a{Vok"*y - the same as (1), but selecting {} block is done multiple times - would work for code blocks that have 7 inner {} braces.
But the thing is - the (1) command works fine when called from a vim function, but (2) misbehaves and selects wrong code block when called from a vim function:
function! CopyCodeBlockToClipboard ()
let cursor_pos = getpos('.')
execute "normal" 'va{a{a{a{a{a{a{Vok"*y'
call setpos('.', cursor_pos)
endfunction
" Copy code block to clipboard
map <C-q> :call CopyCodeBlockToClipboard()<CR>
What am I doing wrong here in the CopyCodeBlockToClipboard?
The (2) command works as expected when executed directly in vim.
UPDATE:
I've noticed that:
if there are more a{ then the included blocks in the function
then vim wouldn't execute V
Looks like vim handles errors differently here. Extra a{ produces some error and regular command execution just ignores it. But execution from withing a function via :normal fails and wouldn't call V (or probably any command that follows the error).
Any workaround for this?
Try this function
function! CopyCodeBlockToClipboard()
let cursor_pos = getpos('.')
let i = 1
let done = 0
while !done
call setpos('.', cursor_pos)
execute "normal" 'v' . i . 'aBVok"*y'
if mode() =~ "^[vV]"
let done = 1
else
let i = i + 1
endif
endwhile
execute "normal \<ESC>"
call setpos('.', cursor_pos)
endfunction
This preforms a execute command to select blocks until it fails to select a block larger block. ([count]aB selects [count] blocks) It seems when the selection fails we end up in visual mode. So we can use mode() to check this.
When this function exits you should be in normal mode and the cursor should be restored to where you started. And the function will be in the * register.
This macro should come close to what you want to achieve:
?Function<CR> jump to first Function before the cursor position
v enter visual mode
/{<CR> extend it to next {
% extend it to the closing }
"*y yank into the system clipboard