1. 程式人生 > >Win32命令列引數的傳入和獲取

Win32命令列引數的傳入和獲取

Win32控制檯,如何傳入和獲取命令列引數的有關問題,

有幾種解決辦法,

總結出來,朋友們一起分享

// tt.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <iostream>
#include "afxinet.h"
#include <Windows.h>
#include <ShellAPI.h>
using namespace std;
#define BUFSIZE MAX_PATH

int _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;
}