RunAs - built-in

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
BarryG
Addict
Addict
Posts: 4123
Joined: Thu Apr 18, 2019 8:17 am

Re: RunAs - built-in

Post by BarryG »

I just modified Trond's code to include an error description, so that it now looks like this:

Code: Select all

#LOGON_WITH_PROFILE = 1
Advapi = OpenLibrary(#PB_Any, "advapi32.dll")
Prototype PCPWLW(A, B, C, D, E, F, G, H, I, J, K)
Global CreateProcessWithLogonW.PCPWLW = GetFunction(Advapi, "CreateProcessWithLogonW")

Procedure.s RunAs(Program.s, User.s, Password.s)
  pi.PROCESS_INFORMATION
  ok = CreateProcessWithLogonW(@User, 0, @Password, #LOGON_WITH_PROFILE, 0, @Program, 0, 0, 0, 0, @pi)
  If ok=0
    error$=Space(255)
    FormatMessage_(#FORMAT_MESSAGE_FROM_SYSTEM,0,GetLastError_(),#LANG_NEUTRAL,@error$,250,0)
    error$=Mid(error$,FindString(error$," ")+1) ; Strip error number (user doesn't need it).
    error$=UCase(Left(error$,1))+LCase(Mid(error$,2)) ; Make it title case.
    error$=RemoveString(error$,#CRLF$) ; Remove trailing blank line.
  EndIf
  CloseHandle_(pi\hProcess)
  CloseHandle_(pi\hThread)
  ProcedureReturn error$
EndProcedure

Debug RunAs("user","pass","D:\WinAmp\Winamppppp.exe")
Now, when I run that standalone code, the Debug correctly says System cannot find the file specified (due to mispelling of the exe name).

But when I call that procedure from my main app, it also fails to launch Winamp but the error reason is Operation completed successfully. WTF? I wanted to show the user the reason for the failure in a messagebox, but I obviously can't show them that. So why does running it standalone like above, show a different error reason when integrated into my app? My app is just calling RunAs() like above, no different.

It's like GetLastError_() is returning an error message for something else? If so, how do I make it valid for CreateProcessWithLogonW in my procedure? Thanks.
Post Reply