gpt4 book ai didi

c++ - 允许表单接受命令行参数

转载 作者:行者123 更新时间:2023-11-28 07:36:41 25 4
gpt4 key购买 nike

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

据我了解,这意味着当用户双击该应用程序时,被双击的文件会将其完整路径作为 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));
}

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

我想知道问题可能是什么和/或是否有更简单的方法。

备注:

我是在 Visual Studio 2003 中编写的,因此某些在更高版本中有效的操作对我来说可能无法实现。

最佳答案

我只需要传递参数 [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();
}

关于c++ - 允许表单接受命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16658804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com