How to add administrator privileges to AutoHotkey

2019-01-26 19:47发布

问题:

I compiled it to an executable, but to open it I have to right-click and press "Run as administrator". I want it to request admin privileges each time I run it, but how to do it?

I can't do this:

Because then it doesn't work when I copy it to a second computer.

回答1:

Try adding this to the auto-execute section (top of the script):

; If the script is not elevated, relaunch as administrator and kill current instance:

full_command_line := DllCall("GetCommandLine", "str")

if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try ; leads to having the script re-launching itself as administrator
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}

and recompile the script.

For more details read https://autohotkey.com/docs/commands/Run.htm#RunAs.



回答2:

Here's a much simpler code for this purpose:

if not A_IsAdmin
Run *RunAs "%A_ScriptFullPath%"

It will run the script as Admin if it's not already running as Admin.