【问题标题】:Strange behavior in Visual C++ ShellExecute() functionVisual C++ ShellExecute() 函数中的奇怪行为
【发布时间】:2017-02-02 05:46:34
【问题描述】:

我尝试编写一个简短的基于 Visual Studio C++ MFC 对话框的应用程序,但在使用 ShellExecute() 时遇到了一个奇怪的行为。

#include "stdafx.h"
#include <iphlpapi.h>
#include "Shlwapi.h"
#include "TestShellExecute.h"
#include "TestShellExecuteDlg.h"

// CTestShellExecuteApp
BEGIN_MESSAGE_MAP(CTestShellExecuteApp, CWinApp)
    ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()

// The one and only CTestShellExecuteApp object
CTestShellExecuteApp theApp;

// CTestShellExecuteApp initialization
BOOL CTestShellExecuteApp::InitInstance()
{
    CWinApp::InitInstance();

    INT_PTR nResponse;
    if (PathFileExists(TEXT("Config.ini")))
        nResponse = IDOK;
    else
    {
        CTestShellExecuteDlg dlg;
        m_pMainWnd = &dlg;
        nResponse = dlg.DoModal();
    }
    if (nResponse == IDOK)
        ExecuteApp();
    return FALSE;
}

void CTestShellExecuteApp::ExecuteApp(void)
{
    ShellExecute(NULL, TEXT("open"), TEXT("notepad"), 
        TEXT("test.txt"), NULL, SW_SHOWNORMAL);
    return;
}

如果文件“Config.ini”存在,代码直接转到 ShellExecute() 并且记事本可以正常启动。

当“Config.ini”文件不存在时,代码会打开一个只有OK和Cancel的对话框。

按下 OK 后,对话框返回并运行 ShellExecute()。记事本没有启动。如果我注释掉m_pMainWnd = &amp;dlg;这行,那么在对话框返回IDOK后,记事本就会启动。

有人可以解释这种行为吗?

【问题讨论】:

  • 什么是 m_pMainWnd?
  • m_pMainWnd 是主窗口。由于这是一个对话框应用程序,因此对话框是主窗口。此行由 MFC 向导生成。

标签: mfc shellexecute


【解决方案1】:

这似乎只是一个时间问题(如果您设置了m_pMainWnd,则完成了更多清理工作)。如果我在ShellExecute 之后添加Sleep(300);,它就可以工作。您应该记住,ShellExecute 的某些操作可能是异步完成的(例如 DDE)。我会考虑使用SEE_MASK_NOASYNC 切换到ShellExecuteEx 或在终止之前添加Sleep

请不要忘记按照ShellExecute documentation on MSDN 中明确说明的方式初始化 COM。

【讨论】:

  • 在 ShellExecute() 之后放置 Sleep(300) 确实解决了问题。我尝试将 ShellExecuteEx() 与 SEE_MASK_NOASYNC 一起使用,其行为与 ShellExecute() 相同。感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多