C语言-windows程序获取管理员权限

当前程序给自己获取管理员权限


#include <stdio.h>
#include <conio.h>
#include <windows.h>
VOID ManagerRun(LPCSTR exe,LPCSTR param)
{ //注意:会跳出提示。
    SHELLEXECUTEINFO ShExecInfo;
    ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ;
    ShExecInfo.hwnd = NULL;
    ShExecInfo.lpVerb = "runas";
    ShExecInfo.lpFile = exe;
    ShExecInfo.lpParameters = param;
    ShExecInfo.lpDirectory = NULL;
    ShExecInfo.nShow = SW_SHOW;
    ShExecInfo.hInstApp = NULL;
    BOOL ret = ShellExecuteEx(&ShExecInfo);
    //杀掉当前线程
    CloseHandle(ShExecInfo.hProcess);
    return;
}
int main(int argc,char *argv[]) {
    if(argc == 1) //初次运行,即双击EXE
    {
        ShowWindow(GetConsoleWindow(),SW_HIDE);
        printf("%s",argv[0]);
        ManagerRun(argv[0],"2");
        return 1;
    }else if(argc == 2) //再次运行,即上面那个ManagerRun
    {
        /*你的程序主代码在此*/
        printf("%s","hello world\n");
       
        getch();
    }
    return 0;
}

打开指定的exe以管理员权限运行


#include <stdio.h>
#include <conio.h>
#include <windows.h>
VOID ManagerRun(LPCSTR exe,LPCSTR param)
{ //注意:会跳出提示。
    SHELLEXECUTEINFO ShExecInfo;
    ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ;
    ShExecInfo.hwnd = NULL;
    ShExecInfo.lpVerb = "runas";
    ShExecInfo.lpFile = exe;
    ShExecInfo.lpParameters = param;
    ShExecInfo.lpDirectory = NULL;
    ShExecInfo.nShow = SW_SHOW;
    ShExecInfo.hInstApp = NULL;
    BOOL ret = ShellExecuteEx(&ShExecInfo);
    //杀掉当前线程
    CloseHandle(ShExecInfo.hProcess);
    return;
}
int main(int argc,char *argv[]) {
    if(argc == 1) //初次运行,即双击EXE
    {
        ShowWindow(GetConsoleWindow(),SW_HIDE);
        printf("%s",argv[0]);
        ManagerRun(argv[0],"2");
        return 1;
    }else if(argc == 2) //再次运行,即上面那个ManagerRun
    {
        /*你的程序主代码在此*/
        printf("%s","hello world\n");
       
        getch();
    }
    return 0;
}

备注cmd.exe可以换成自己需要调用的exe程序(写全路径) , 否则就需要配置环境变量,不然找不到

注意: 不要自己掉自己否则死循环,窗口一直闪