【问题标题】:Allowing a Form to Accept Cmd line arguments允许表单接受命令行参数
【发布时间】:2014-11-12 05:20:35
【问题描述】:

我有一个应用程序现在有一个可以加载的设置文件。我希望为用户提供的一项功能是双击我创建的特定文件类型并让应用程序打开文件。

据我了解,这意味着当用户双击应用程序时,被双击的文件会将其完整路径作为 cmdline 参数传递给我的应用程序。

为了加载此文件,我尝试在我的 Form1.cpp 文件中执行以下操作:

#include "stdafx.h"
#include "Form1.h"
#include <windows.h>
//Command Line Args
#include <shellapi.h>

using namespace JohnDeereDataqGUI;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
int argCount;
LPWSTR * argList;
argList = CommandLineToArgvW(GetCommandLineW(), &argCount);
Application::Run(new Form1(argList[0]));
LocalFree(argList);
return 0;
}

对于我的构造函数:

public:
    Form1(String * argument)
    {
        InitializeComponent();
        if(argument)
            loadPreviousSettings((const char *)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(argument));
    }

目前,当我双击我指定类型的文件时,文件不会加载。我的应用程序加载,但设置设置为默认值,而不是存储在应该加载的文件中的自定义设置。此外,我在尝试调试时遇到问题,因为我无法在调试模式下运行应用程序,然后双击计算机上的文件,因为它会启动一个单独的 .exe,当然不会遇到断点。

我想知道问题可能是什么和/或是否有更简单的方法来做到这一点。

注意:

我在 Visual Studio 2003 中编写此代码,因此我可能无法在更高版本中执行某些操作。

【问题讨论】:

  • 您可以通过在项目的 Visual Studio 调试器设置中设置其命令行和工作目录来调试它。或者在_tWinMain 的开头加上一个Sleep,然后将调试器附加到它上面。
  • 谢谢,我刚刚使用调试器设置中的命令行选项传入了参数,发现这是我想要的第二个参数。

标签: c++ winforms command-line command-line-arguments


【解决方案1】:

我只需要传递参数 [1] 而不是参数 [0],因为 [0] 是应用程序的路径,而 [1] 是我要传递的文件。简单的错误。

最终解决方案:

#include "stdafx.h"
#include "Form1.h"
#include <windows.h>
//Command Line Args
#include <shellapi.h>

using namespace JohnDeereDataqGUI;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
int argCount;
LPWSTR * argList;
argList = CommandLineToArgvW(GetCommandLineW(), &argCount);
if( argCount > 1)
    Application::Run(new Form1(argList[1]));
else
    Application::Run(new Form1());
LocalFree(argList);
return 0;
 }

还有:

 Form1(String * argument)
    {
        InitializeComponent();
        if(argument)
            loadPreviousSettings((const char *)(void*)     System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(argument));
    }
    Form1(void)
    {
        InitializeComponent();
    }

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2013-11-24
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多