Win32命令行参数的传入和获取
Win32控制台,如何传入和获取命令行参数的有关问题,
有几种解决办法,
总结出来,朋友们一起分享
// tt.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include "afxinet.h"#include <Windows.h>#include <ShellAPI.h>using namespace std;#define BUFSIZE MAX_PATHint _tmain(int argc, _TCHAR* argv[]){///*************//传入或者获取win32命令行传参数//**************///方法一wstring strExePath=L"C:\\Program Files\\111.exe";wstring strParamete=L"W";ShellExecute(NULL, _T("open"), strExePath.c_str(), strParamete.c_str(), NULL, SW_SHOWNORMAL);////方法二///**********////这种传参数的方法不可行//argv[1]=L"C:\\111.exe";//argv[2]=L"G";//***********/////方法三 使用for循环 for(int i=0; i< argc; i++){_TCHAR* Str_Cmd = argv[i];string sStr_Cmd ;//Unicode转换为ASCII,也即是宽字节转换为单字符,代码int UnicLen;UnicLen=::WideCharToMultiByte(CP_UTF8,NULL,Str_Cmd,wcslen(Str_Cmd),NULL,0,NULL,NULL);char*str_ASCII=new char[UnicLen+1];ZeroMemory(str_ASCII,UnicLen+1);::WideCharToMultiByte(CP_UTF8,NULL,Str_Cmd,wcslen(Str_Cmd),str_ASCII,UnicLen,NULL,NULL);str_ASCII[UnicLen]='\0';/////////sStr_Cmd = str_ASCII;wcout<<sStr_Cmd.c_str()<<endl;}/**************方法四GetCommandLineW()***************//*wstring str_cmd;str_cmd = ::GetCommandLineW();*//**************方法五CommandLineToArgvW()***************//**LPWSTR *szArgList; int argCount; szArgList = CommandLineToArgvW(GetCommandLine(), &argCount); if (szArgList == NULL) { MessageBox(NULL, L"Unable to parse command line", L"Error", MB_OK); return 10; } for(int i = 0; i < argCount; i++) { MessageBox(NULL, szArgList[i], L"Arglist contents", MB_OK); } LocalFree(szArgList); ***///判断结果if(argc == 1){cout<<"命令行没有参数"<<endl;//return 0;}else if(argc == 2){cout<<"命令行一个参数"<<endl;}else{cout<<"命令行两个参数"<<endl;} //方法六 AfxGetApp()->m_lpCmdLine;return true;}