命令行参数wmain (int argc,wchar_t *argv[])

来源:互联网 发布:smtp服务器端口25 编辑:程序博客网 时间:2024/05/21 05:07

命令参数,总是把我搞得头晕,这回决定把它一次弄清
启动程序时,系统会在传入命令行参数给程序
比如下面,
ipconfig /all
 显示完整网络配置信息。
%windir%\system32\rundll32.exe powrprof.dll,SetSuspendState
这个在启用休眠的电脑上运行,立即进入休眠
同样
shutdown /h 
也能休眠
....
如下图所示
ttt是程序名,它和它后面的东西一起在启动程序时就传给了程序
一般的命令行程序就可以从argc,argv中取得所有的参数
但是如果是windows程序呢,下面就来讲


这是测试代码

//cl ttt.cpp//ttt  The last  straw that breaks the camel's back#include <windows.h>#include <tchar.h>#include <stdio.h>#include <locale.h>//让wprintf()支持中文#pragma comment(lib,"shell32.lib")int wmain (int argc,wchar_t *argv[]) {setlocale(LC_CTYPE,"CHS");//让wprintf()支持中文wprintf(L"main (int argc,char *argv[])\n");wprintf(L"命令行中可执行文件名argv[0]为:%s",argv[0]); wprintf(L"总共有argc:%d个参数:\n",argc); for(int i=0;i<argc;i++){wprintf(L"[%d]:%s\n",i,argv[i]);}int nargs;WCHAR *psz=GetCommandLineW();wprintf(L"GetCommandLineW()返回:%s\n\n",psz);wprintf(L"CommandLineToArgvW(GetCommandLineW(),&nargs):\n");WCHAR **pszcmdlist=CommandLineToArgvW(psz,&nargs);if(pszcmdlist!=NULL){for(int i=0;i<nargs;i++){wprintf(L"%d,%s\n",i,pszcmdlist[i]);}LocalFree(pszcmdlist);//记得释放pszcmdlist=NULL;}}
如何取得完整路径的程序名呢?
如何取得程序路径?
还有程序的执行映像名呢?

找到了这几个API:GetModuleFileNameW()  GetCurrentDirectoryW() GetFileTitleW() 



完整的源代码
#include <windows.h>#include <tchar.h>#include <stdio.h>#include <locale.h>//让wprintf()支持中文#include <atlstr.h>#pragma comment(lib,"shell32.lib")#pragma comment(lib,"comdlg32.lib")int wmain (int argc,wchar_t *argv[]) {setlocale(LC_CTYPE,"CHS");//让wprintf()支持中文wprintf(L"main (int argc,char *argv[])\n");wprintf(L"命令行中可执行文件名argv[0]为:%s",argv[0]); wprintf(L"总共有argc:%d个参数:\n",argc); for(int i=0;i<argc;i++){wprintf(L"[%d]:%s\n",i,argv[i]);}int nargs;WCHAR *psz=GetCommandLineW();wprintf(L"GetCommandLineW()返回:%s\n\n",psz);wprintf(L"CommandLineToArgvW(GetCommandLineW(),&nargs):\n");WCHAR **pszcmdlist=CommandLineToArgvW(psz,&nargs);if(pszcmdlist!=NULL){for(int i=0;i<nargs;i++){wprintf(L"%d,%s\n",i,pszcmdlist[i]);}LocalFree(pszcmdlist);//记得释放pszcmdlist=NULL;}WCHAR AppFileFullName[MAX_PATH];GetModuleFileNameW(NULL,AppFileFullName,MAX_PATH);wprintf(L"完整路径的程序名:%s\n",AppFileFullName);WCHAR AppFileTitleName[MAX_PATH];GetFileTitleW(AppFileFullName,AppFileTitleName,sizeof(AppFileTitleName));wprintf(L"程序标题名:%s\n",AppFileTitleName);WCHAR AppDirectory[MAX_PATH];GetCurrentDirectoryW(sizeof(AppDirectory),AppDirectory);wprintf(L"程序路径:%s\n",AppDirectory);}


0 0
原创粉丝点击