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 <windows.h>

int main(void)
{
    
    
    SHELLEXECUTEINFO sei = {
    
     sizeof(SHELLEXECUTEINFO) };
    sei.lpVerb = TEXT("runas");
    sei.lpFile = TEXT("cmd.exe");//add  application  which you want to run as administrator here
    sei.nShow = SW_SHOWNORMAL;//without this,the windows will be hiden
    if (!ShellExecuteEx(&sei))
    {
    
    
        DWORD dwStatus = GetLastError();
        if (dwStatus == ERROR_CANCELLED)
        {
    
    
            printf("提升权限被用户拒绝\n");
        }
        else if (dwStatus == ERROR_FILE_NOT_FOUND)
        {
    
    
            printf("所要执行的文件没有找到\n");
        }
    }

    getchar();
    return 0;
}

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

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

猜你喜欢

转载自blog.csdn.net/weixin_45203607/article/details/125657068
今日推荐