I'm writing a (Win32 Console) program that wraps another process; it takes parameters as in the following example:
runas.exe user notepad foo.txt
That is: runas
parses user
and then will run notepad, passing the remaining parameters.
My problem is that argv
is broken down into individual parameters, but CreateProcessAsUser
requires a single lpszCommandLine
parameter.
Building this command line is probably not as simple as just joining argv
back together with spaces. Any pointers?
This is just an example. My first argument isn't actually a user name, and might have spaces in it. This makes manually parsing the result of GetCommandLine
tricky.
Similarly, a naive concatenation of argv
won't work, because it needs to deal with the case where the original arguments were quoted and might have spaces in them.
Manually recombining them is hard:
You could try to re-combine them, I think it would work, but be sure to following the same command line escaping rules that windows has. This could be more than the trivial solution you're looking for.
Also if there are any parameters that have spaces in them, then you would want to join them to the string with quotes around them. Here is an example of a strange escaping rule: if you have --folderpath "c:\test\"
then the last backslash has to be doubled --folderpath "c:\test\\"
.
If you are using MFC:
You can can get the value you want from your derived CWinApp's theApp.m_lpCmdLine. Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.
If you are using Win32 only (even without a GUI):
You can get it from WinMain. Which can be your program's entry point.
Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.
If you must use a console based application with main or wmain:
The Win32 API GetCommandLine seems to be the way to go. You would need to still parse this to get past the .exe name though. Take into account quotes around the exe name/path too. If there are no such quotes at the start, then just go to the next space for the start.
You can use the GetCommandLine function.
Why not use 'WinMain' instead of 'main'? This should give you the string in the format you want.
There is Win32 API call that returns command line: GetCommandLine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With