win32命令行参数

在开发win32程序时,经常要对命令行参数进行处理,例如一个安装程序,我们希望提供参数,使得程序可以通过批处理进行自动安装。

1.main函数参数获取

main函数的参数获取非常简单,并且main的参数已经把命令行参数分割出来了,简单对命令行参数进行打印:

#include<stdio.h>
int main(int argc, char *argv[])
{
	int i;
	printf("%d\n", argc);
	for (i = 0; i < argc;++i)
	{
		printf("%s\n", argv[i]);
	}
	return 0;
}

argc:命令行参数个数

argv:保存了命令行参数,第一个是程序名字

在cmd下运行该程序:

2.WinMain函数获得参数

WinMain的原型如下:

int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)

WinMain是gui程序入口,lpCmdLine保存了命令行参数,但是完整的命令行参数,要对命令行进行分割,windows的API提供了CommandLineToArgvW()函数对宽字符命令行参数的切割,如果想是想获得char *的命令行参数需要直接对lpCmdLine进行手动切割,或者对将宽字符转为多字节。

GetCommandLine函数可以获得命令行参数,其实就是lpCmdLine这个参数,但GetCommandLine会通过宏替换自动进行调用GetCommandLineW()函数。

#include<windows.h>
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
	int argc = 0;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc);
	for (int i = 0; i < argc;++i)
	{
		MessageBox(0, argv[i], L"cmdLine", 0);
	}
}

windows也提供了宽字符转化为多字节的函数接口:WideCharToMultiByte

#include<windows.h>
#include<string.h>
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
	int argc = 0;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc);
/*	for (int i = 0; i < argc;++i)
	{
		MessageBox(0, argv[i], L"cmdLine", 0);
	}*/
	for (int i=0; i < argc; ++i)
	{
		LPWSTR cmd = argv[i];
		int len;
		len = WideCharToMultiByte(CP_UTF8, NULL, cmd, wcslen(cmd), NULL, 0, NULL, NULL);
		char *str_ascii = new char[len + 1];
		ZeroMemory(str_ascii, len + 1);
		WideCharToMultiByte(CP_UTF8, NULL, cmd, wcslen(cmd), str_ascii, len, NULL, NULL);
		str_ascii[len] = '\0';
		if (strcmp(str_ascii, "-u") == 0)
		{
			MessageBox(0, L"-u", L"cmdLine", 0);
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值