Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to run dos command in administrator privilage while in c++ code?

42 views
Skip to first unread message

Yang Luo

unread,
Jan 18, 2016, 8:34:08 AM1/18/16
to
I use dos command "net", need administrator privilage.Now I need put this command into c++ code, I use system() function, like this 'system("net
use S: \\computername\foldername");', So how can I improve dos command excute privilage while running c++ code.

Alf P. Steinbach

unread,
Jan 18, 2016, 8:54:04 AM1/18/16
to
There are two main ways for you, assuming (as the question indicates)
that you don't want to have your C++ program running elevated.

First, you can create a shortcut that provides elevation. That's all you
need directly, but for completeness I mention that you can use that to
provide a batch file "run elevated" command, to some degree like
Unix-land "sudo". In order to run a shortcut via the C++ `system`
function, I think you can just specify its full name, with ".lnk"
filename extension. For some inexplicable reason the ".lnk" extension is
not in the PATHEXT list, which means that by default you cannot omit the
extension.

Second, from the C++ code you can use the Windows API function
ShellExecute, with "runas" argument.

There is also a third way to run code elevated, which is a bit advanced,
namely using a COM interface that's used by ShellExecute internally.

But I'd go for the simple shortcut, which as it happens is a
programming-language-agnostic solution.


Cheers & hth.,

- Alf

PS: A question like this is much better asked in a Windows-specific
group, at least wrt. the goal of keeping the groups clean & useful.
There is a little bit of C++ relevance in the question, e.g. it mentions
C++. But mostly and primarily this is about Windows, independent of
programming language, i.e. OFF TOPIC in this group.
Message has been deleted

Yang Luo

unread,
Jan 19, 2016, 7:13:43 AM1/19/16
to
在 2016年1月18日星期一 UTC+8下午9:54:04,Alf P. Steinbach写道:
Thanks,Alf.

Yang Luo

unread,
Jan 21, 2016, 4:15:14 AM1/21/16
to
This is a example
SHELLEXECUTEINFO sei={0};//
sei.cbSize=sizeof(SHELLEXECUTEINFO);
sei.fMask=SEE_MASK_NOCLOSEPROCESS;
sei.hwnd=NULL;
sei.lpVerb=NULL;//_T("open");//_T("runas")
sei.lpFile=_T("cmd.exe");
sei.lpParameters=strParameters;
sei.lpDirectory =NULL;//_T("D:")
sei.nShow=SW_HIDE;
sei.hInstApp=NULL;
if(!ShellExecuteEx(&sei)){
DWORD dwStatus = GetLastError();
if(dwStatus == ERROR_CANCELLED)AfxMessageBox(_T("提升权限被用户拒绝"));
else if(dwStatus == ERROR_FILE_NOT_FOUND)AfxMessageBox(_T("所要执行文件没有找到"));
}
WaitForSingleObject(sei.hProcess,INFINITE);
0 new messages