我正在尝试从elevated(has admin privileage) c++ application
执行command prompt
中的netsh winsock reset catalog
命令。
HINSTANCE retVal = SExecute(NULL, "open", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
它只是打开命令提示符,没有其他事情发生。我试过
HINSTANCE retVal = SExecute(NULL, "runas", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
和
HINSTANCE retVal = SExecute(NULL, "open", "cmd", " netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
开关字符导致问题。当开关字符从\c
更改为/c
时,它起作用。
Form
HINSTANCE retVal = SExecute(NULL, "open", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
到
HINSTANCE retVal = SExecute(NULL, "open", "cmd", "/c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
花了一些试验和错误找到最佳的方式,所以我想分享my solution。抛开我的 recomendation 使用异步调用,这里是我的 DoRun()函数:
BOOL DoRun(WCHAR *command)
{
BOOL Result = FALSE;
DWORD retSize;
LPTSTR pTemp = NULL;
TCHAR Command[BUFSIZE] = L"";
if (!(DeleteFile(RESULTS_FILE)))
{
//return L"Can't delete previous results";
}
_tcscpy_s(Command, L"/C ");
_tc_s(Command, command);
_tc_s(Command, L" >");
_tc_s(Command, RESULTS_FILE);
wprintf(L"Calling:\n%s\n", Command);
Result = (BOOL) SExecute(GetActiveWindow(), L"OPEN", L"cmd", Command, NULL, 0L);
if(!Result)
{
retSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL,
GetLastError(),
LANG_NEUTRAL,
(LPTSTR)&pTemp,
0,
NULL);
MessageBox(NULL,pTemp,L"Error",MB_OK);
}
return Result;
}
func runElevated(interName, stateName string, isAdmin bool) {
/*
禁用无线网卡:netsh intece set intece WLAN disabled
启用无线网卡:netsh intece set intece WLAN enabled
禁用有线网卡:netsh intece set intece 以太网 disabled
启用有线网卡:netsh intece set intece 以太网 enabled
*/
var verb string
if isAdmin {
verb = "open"
} else {
verb = "runas"
}
exe := "C:\\Windows\\system32\\cmd.exe" // or "cmd"
cwd, _ := os.Getwd()
var cmdList = make([]string, 0)
var cmdMap = map[string]string{"WLAN": "以太网", "enable": "disable", "以太网": "WLAN", "disable": "enable"}
cmdList = append(cmdList, fmt.Sprintf("/c netsh intece set intece %s %s", interName, stateName))
cmdList = append(cmdList, fmt.Sprintf("/c netsh intece set intece %s %s", cmdMap[interName], cmdMap[stateName]))
verbPtr, _ := syscall.UTF16PtrFromString(verb)
exePtr, _ := syscall.UTF16PtrFromString(exe)
cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
for _, k := range cmdList {
argPtr, _ := syscall.UTF16PtrFromString(k)
err := windows.SExecute(0, verbPtr, exePtr, argPtr, cwdPtr, windows.SW_HIDE)
if err != nil {
log.Fatalf("execute error, detail %s", err)
}
}
log.Fatal("execute success...")
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(39条)