对于我的 MFC 应用程序,我想要类似的东西,但是我发现接受的答案对我来说只是部分解决方案。如果 MFC 应用程序启动时在命令行中指定了文件名,则使用接受的答案将无法打开该文件。
我想 (1) 在从命令行调用 MFC 应用程序时允许打开文件,以及 (2) 更改当前工作文件夹。
在扩展 CWinAppEx 的应用程序的 InitInstance() 覆盖中,我使用了以下源:
// determine the user's home folder for documents such as C:\user\xxx\Documents
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, 0, CMFCApplication4Doc::m_UserDocumentsFolder))) {
PathAppend(CMFCApplication4Doc::m_UserDocumentsFolder, L"GenPOS BO");
TRACE1("home path found %s\n", CMFCApplication4Doc::m_UserDocumentsFolder);
if (!CreateDirectory(CMFCApplication4Doc::m_UserDocumentsFolder, NULL)) {
DWORD dwLastError = GetLastError();
if (dwLastError != ERROR_ALREADY_EXISTS) {
// may be ERROR_PATH_NOT_FOUND indicating intermediate directories do not exist.
// CreateDirectory() will only create the final folder in the path so intermediate folders
// must already exist.
TRACE1("CreateDirectory error %d\n", dwLastError);
}
}
SetCurrentDirectory(CMFCApplication4Doc::m_UserDocumentsFolder);
}
else {
TRACE0("home path not found");
}
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) // actually none
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The main window has been initialized, so show and update it
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();