我将其编译为可执行文件,但要打开它,我必须右键单击并按“以管理员身份运行”。我希望它每次运行时都请求管理员权限,但该怎么做?
我做不到:
因为当我将其复制到第二台计算机时它不起作用。
尝试将其添加到自动执行部分(脚本顶部):
; 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
}
并重新编译脚本。
有关更多详细信息,请阅读 https://autohotkey.com/docs/commands/Run.htm#RunAs。
这里有一个更简单的代码用于此目的:
#SingleInstance Force
if not A_IsAdmin
Run *RunAs "%A_ScriptFullPath%"
如果尚未以管理员身份运行脚本,它将以管理员身份运行脚本。
如果您的脚本顶部没有
#SingleInstance Force
,它会询问您是否要将正在运行的脚本(不是admin)替换为admin。因此,为了防止这种情况,请在脚本顶部添加提到的行。
如果您将来可能会编译脚本,最好使用这个脚本以使其面向未来:
#SingleInstance Force
if !A_IsAdmin
Run, % "*RunAs " (A_IsCompiled ? "" : A_AhkPath " ") Chr(34) A_ScriptFullPath Chr(34)
Chr(34)
返回字符 "
在 AHK V2 中
#SingleInstance Force
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
try
{
if A_IsCompiled
Run '*RunAs "' A_ScriptFullPath '" /restart'
else
Run '*RunAs "' A_AhkPath '" /restart "' A_ScriptFullPath '"'
}
ExitApp
}
If (!A_IsAdmin) ; IF NOT Admin
{
Run, *RunAs "%A_ScriptFullPath%" ; Run script as admin
ExitApp ; Exit the current instance running without admin privileges
}
MsgBox, 262144, , Running with admin privileges! ; Continue your code...