zoukankan      html  css  js  c++  java
  • Win32程序支持命令行参数的做法(转载)

    转载:http://www.cnblogs.com/lanzhi/p/6470406.html

    转载:http://blog.csdn.net/kelsel/article/details/52759001

     首先说说Win 32 API程序如何支持命令行参数。Win 32程序的入口函数为:

    int APIENTRY _tWinMain(HINSTANCE hInstance,  
                         HINSTANCE hPrevInstance,  
                         LPTSTR    lpCmdLine,  
                         int       nCmdShow)  

     其中lpCmdLine为命令行参数,所以只需把它解析出来即可。

    比如一个win32程序为a.exe,它的命令行用法如下:

    a.exe 文件1 文件2

    那么可以这样解析:

    int APIENTRY _tWinMain(HINSTANCE hInstance,  
                         HINSTANCE hPrevInstance,  
                         LPTSTR    lpCmdLine,  
                         int       nCmdShow)  
    {  
       
        int argc = 0;  
        LPWSTR *lpszArgv = NULL;  
    //分割命令行参数  
        lpszArgv = CommandLineToArgvW(lpCmdLine, &argc);  
        if (argc >= 2)  
        {  
            if(::GetFileAttributes(lpszArgv[0])==-1)  
            {  
                //文件1不存在  
                ::MessageBox(GetDesktopWindow(),lpszArgv[1],_T("提示"), MB_OK|MB_ICONINFORMATION);  
                return 1;  
            }  
          
            if(::GetFileAttributes(lpszArgv[1])==-1)  
            {  
                //文件2不存在  
                ::MessageBox(GetDesktopWindow(),lpszArgv[2],_T("提示"), MB_OK|MB_ICONINFORMATION);  
                return 1;  
            }  
    }  

    如果是一个MFC程序,做法比Win 32 API程序多一步,就是获取命令行字符串。具体如下:

    BOOL CXxxAppApp::InitInstance()  
    {  
       LPTSTR pszCmdLine = GetCommandLine(); //获取命令行参数;  
        LPWSTR *lpszArgv = NULL;  
        int argc = 0;  
        lpszArgv = CommandLineToArgvW(pszCmdLine,&argc); //拆分命令行参数字符串  
    // 下面的处理和win32 api程序一样,  
    }  

    有四点需要注意:

    1. Win 32 API程序的命令行lpCmdLine是只包含参数,而MFC程序的命令行第一个参数是exe本身。

    2.  GetCommandLine获取的是一个unicode字符串,CommandLineToArgvW也只能处理unicode字符串,如果你的程序选择的是多字节字符集,需要进行处理。

    3.  CommandLineToArgvW是按空格来拆分参数的,如果从参数是文件路径,就不要用CommandLineToArgvW了,因为文件路径本身可能带有空格,可以用正则表达式来解析。

    4.  命令行的调试可以这样设置:

  • 相关阅读:
    redis 数据类型详解 以及 redis适用场景场合
    angular.js记录
    Python chr() 函数
    Python frozenset() 函数
    Python 字典 dict() 函数
    Python set() 函数
    Python tuple 函数
    Python eval() 函数
    Python repr() 函数
    Python str() 函数
  • 原文地址:https://www.cnblogs.com/chechen/p/6874565.html
Copyright © 2011-2022 走看看